JavaScript Object原型函数无法按预期使用

问题描述

| 如果您打开此JSfiddle,您应该在Firebug / Chrome开发工具中看到调用ѭ0is时会引发异常,因为ѭ1不存在。 但是,如果您在控制台中运行
Object.method
Function.method
,您会发现它们确实存在于各自的原型中。 我确定这是一个简单的继承问题,但是在这一点上我无法理解为什么
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;
};
向Function原型添加一个方法。使用构造函数创建对象:使用
new
关键字调用的函数将创建其构造的对象的实例。在
Object.create
\'shim \'中,构造函数为
F
,但shim返回其实例(
new F()
)。 变量“ 5”不是构造函数,而是实例。您只能从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!
    ,        这可行,但是没有控制台
Object.prototype.method = function (name,func) {
    this[name] = func;
};
http://jsfiddle.net/mplungjan/jhBjs/     ,        我相信您要的不是20英镑,而是19英镑。另外我猜你想在对象上:
Object.prototype.method = function (name,func) {
    this.[name] = func
    return this
}
鉴于您已经在使用Crockford的对象了,如果您并非所有22岁的孩子都需要使用此对象,则可以执行以下操作:
var X = { method: function (name,func) {
    this[name] = func
    return this
}

var x = Object.create(X)
    ,        var x,x是一个Object,而不是一个函数,这就是为什么您需要使用
Object.prototype.method = function (name,func) {    
  this[name] = func;    
  return this;
};