了解Crockford引入的高级方法 [英] Understanding the superior method introduced by Crockford

查看:56
本文介绍了了解Crockford引入的高级方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在功能继承模式中,Crockford通过以下方式引入了新的superior方法:

In the functional inheritance pattern, Crockford introduces a new superior method via:

Object.method('superior', function (name) {
    var that = this,
    method = that[name];
    return function () {
        return method.apply(that, arguments);
    };
});

method所在的位置:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

示例:

var coolcat = function (spec) {
    var that = cat(spec),
        super_get_name = that.superior('get_name');
    that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};

我的问题是为什么不只将that.get_name分配给super_get_name?

My question is Why don't just assign that.get_name to super_get_name ?

推荐答案

我的问题是为什么不只将that.get_name分配给super_get_name?"

"My question is Why don't just assign that.get_name to super_get_name?"

由于get_name方法将其this值设置为that对象的方式是通过将其调用为:

Because the way the get_name method has its this value set to the that object is by invoking it as:

that.get_name();

当调用函数作为对象的方法时,该对象在该函数调用中成为this的值.

When a function is invoked as the method of an object, the object becomes the value of this in that invocation of the function.

如果您这样做,则:

var super_get_name = that.get_name;

super_get_name();

现在您要调用一个分离的函数,因此它不知道其this值应该是什么,因此它使用默认值,通常是window对象.

Now you're invoking a detached function, so it doesn't know what its this value should be, and so it uses the default, which is usually the window object.

我根本不喜欢克罗克福德展示的解决方案.通常,在那种情况下,您只需要在那里创建一个新函数,而不是依靠Object.prototype的扩展来为您完成此功能. (扩展Object.prototype是非常难看的IMO.)

I don't like the solution that crockford shows at all. Typically, in that situation, you'd simply make a new function right there instead of relying on extensions to Object.prototype to do it for you. (Extending Object.prototype is very ugly IMO.)

var coolcat = function (spec) {
    var that = cat(spec),
        _original_get_name = that.get_name,
        super_get_name = function() {
                             return _original_get_name.apply(that, arguments);
                         };

    that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};


或者在现代的实现中,您将使用Function.prototype.bind创建一个新函数,该函数的this值将绑定到您作为.bind()的第一个参数提供的值.


Or in modern implementations, you'd use Function.prototype.bind to create a new function with its this value bound to whatever you provided as the first argument to .bind().

var coolcat = function (spec) {
    var that = cat(spec),
        super_get_name = that.get_name.bind(that);

    that.get_name = function (n) {
        return 'like ' + super_get_name() + ' baby';
    };
    return that;
};

这篇关于了解Crockford引入的高级方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆