【发布时间】:2017-03-26 05:25:11
【问题描述】:
我正在深入了解原型链,但我在构建函数时遇到了一些困难。我想构建一个函数来接收一个对象并添加到对象的原型中。我做错了什么?
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 原型链接
标签: javascript inheritance prototype