如果你打开this JSFiddle ,您应该在 Firebug/Chrome Dev Tools 中看到当调用 x.method
时抛出异常,因为 method
不存在。
但是,如果您在控制台中运行 Object.method
或 Function.method
,您会发现它们确实存在于各自的原型(prototype)中。
我确信这是一个简单的继承问题,但目前我无法理解为什么 method
方法没有冒泡到 x
对象。
代码如下:
// Crockford's Object.create shim
if (typeof Object.create !== 'function') {
Object.create = function (o) {
var F = function () {};
F.prototype = o;
return new F();
};
}
// Add a method creation function to the Function prototype
// Note that on this line I've also tried:
// Object.prototype.method = Function.prototype.method = function (name, func) {
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
// Create our object
var x = Object.create({});
// Add common methods to the prototype of our new object
x.method('logNumber', function (num) {
console.log(num);
});
// Try it out
x.logNumber(6);
最佳答案
[注意] jsfiddle 目前似乎已关闭,所以我无法检查您的代码
这个函数:
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
向函数原型(prototype)添加一个方法。对象是使用构造函数创建的:使用 new
关键字调用的函数将创建它构造的对象的实例。在 Object.create
'shim' 中,构造函数是 F
,但是 shim 返回它的一个实例 (new F( )
).
变量 x
不是构造函数,而是实例。您只能从 Function.prototype 调用 method
,因此 x.method
是 undefined
。
不使用 Object.create
可能会告诉您它是如何工作的:
function X(){}; //=> new X will create an instance of an empty Object
X.method('logNumber', function (num) {
console.log(num);
}); //=> call 'method' from the constructor: now it's working
var x = new X; //=> create an instance
x.logNumber(6); //=> behold!
关于JavaScript 对象原型(prototype)函数未按预期提供,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6192077/