gpt4 book ai didi

javascript - 原型(prototype)链继承

转载 作者:行者123 更新时间:2023-11-30 08:27:34 25 4
gpt4 key购买 nike

我正在深入研究原型(prototype)链,但在构建函数时遇到了一些困难。我想构建一个函数,它将接收一个对象并添加到该对象的原型(prototype)中。我做错了什么?

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"

最佳答案

我修改了代码。对象没有原型(prototype)。函数具有可用于链接的原型(prototype)。希望这会有所帮助。

function getObject(obj) {
function F() {}
F.prototype = Object.create(obj);

F.prototype.say = function(){
console.log("Hello", this.name);
}.bind(obj);

return new F();
}

var r = getObject({ name: "James"});

console.log(r.name); // James
r.say() // Hello James

关于javascript - 原型(prototype)链继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43025343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com