在函数式继承模式中,Crockford 引入了一个新的superior
方法:
Object.method('superior', function (name) {
var that = this,
method = that[name];
return function () {
return method.apply(that, arguments);
};
});
方法
是:
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
tosuper_get_name
?"
因为 get_name
方法将其 this
值设置为 that
对象的方式是调用它:
that.get_name();
当一个函数作为一个对象的方法被调用时,该对象在该函数的调用中成为 this
的值。
如果您改为这样做:
var super_get_name = that.get_name;
super_get_name();
现在你正在调用一个分离函数,所以它不知道它的 this
值应该是什么,所以它使用默认值,通常是 window
对象。
我根本不喜欢 crockford 展示的解决方案。通常,在那种情况下,您只需在那里创建一个新函数,而不是依靠 Object.prototype
的扩展来为您完成。 (扩展 Object.prototype
在我看来是非常丑陋的。)
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)到您作为第一个参数提供的任何内容.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;
};
关于javascript - 了解 Crockford 介绍的高级方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21332306/