了解Crockford引入的高级方法 [英] Understanding the superior method introduced by 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
tosuper_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屋!