使用 Object.create() 将函数与原型上的属性合并

Merging functions with properties on a prototype using Object.create()

本文关键字:原型 属性 合并 函数 create Object 使用      更新时间:2023-09-26
var blah = (function(){
    function ret(){
    }
    ret.prototype = Object.create(Object.prototype, { 
        getone: {
            get: function() { return 1; }
        },
        funcstuff: function(){ console.log('funcstuff'); }
    });
    return ret;
})();
var b = new blah();
console.log(b.getone); // 1
b.funcstuff(); // Uncaught TypeError: Property 'funcstuff' 
               // of object #<Object> is not a function 

我想知道使用上述Object.create()funcstuff添加到ret原型的正确语法。

http://jsfiddle.net/Qy9Vm/

我想知道使用上面的 Object.create() 将 funcstuff 添加到 ret 原型的正确语法。

由于您提供给Object.create定义属性的对象是属性描述符,因此如果您希望funcstuff实际上是一个函数,则可以将其定义为描述符中的value属性:

ret.prototype = Object.create(Object.prototype, { 
    getone: {
        get: function() { return 1; }
    },
    funcstuff: {                                       // changes
        value: function(){ console.log('funcstuff'); } // changes
    }                                                  // changes
});

我认为正确的语法是:

var blah = (function(){
function ret(){
}
ret.prototype = Object.create(Object.prototype, { 
    getone: {
        get: function() { return 1; }
    },
    funcstuff: { value: function(){ console.log('funcstuff'); } }
    // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
});
return ret;
})();
var b = new blah();
console.log(b.getone); // 1
b.funcstuff();

Object.create()不接受函数或属性,它需要一个属性描述符,该描述符本身是一个具有标准属性的对象,可以像configurableenumerable......等。