我在引擎蓋下圍繞原型鏈,但我在構建函數時遇到了一些困難。我想要構建一個函數來接收對象並添加到對象的原型中。我究竟做錯了什麼?原型鏈繼承
function getObject(obj) {
function F() {}
F.prototype.say = function(){
console.log("Hello", this.name);
}.bind(obj);
obj.prototype = Object.create(F.prototype);
return obj;
}
var r = getObject({ name: "James"});
r.name
r.say()
// r = { name: "James" }
// r.say() "Hello James"
我得到了我正在尋找的東西。我受到限制,不允許使用ES6課程......我知道對不對?
function getObject(obj) {
function F() { }
F.prototype.say = function(){
console.log("Hello", this.name);
};
const output = Object.create(F.prototype);
return Object.assign(output, obj);
}
var r = getObject({ name: "James"});
r // { name: "James" }
r.name // "James"
r.say() // "Hello James"
對象沒有原型屬性函數。他們只有一個dunder proto鏈接 –