JavaScript 对象原型(prototype)函数未按预期提供

标签 javascript prototype-programming

如果你打开this JSFiddle ,您应该在 Firebug/Chrome Dev Tools 中看到当调用 x.method 时抛出异常,因为 method 不存在。

但是,如果您在控制台中运行 Object.methodFunction.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.methodundefined

使用 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/

相关文章:

javascript - 如何在 Node.js 上使用 co 模块捕获异常?

javascript - 对象字面量/初始化器中的自引用

javascript - javascript 是否在原型(prototype)之外存储数据类型信息?

javascript - 如何正确扩展 Object.prototype?

javascript - 使用 Javascript 检索 Sharepoint 列表的字段/列名称

javascript - 无法将菜单按钮向右移动

JavaScript - 基于原型(prototype)的编程 - this.myFunction 不是函数错误

Javascript 原型(prototype)和访问类的问题

javascript - 快捷方式将 jQuery 限制为特定 DOM 节点

self - "Pure"原型(prototype)语言