我把头绕在引擎盖下的原型链上,但我很难建立一个函数。我想要构建一个函数,它将接收一个对象并添加到对象的原型中。我做错了什么?
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"发布于 2017-03-27 05:59:39
我修改了密码。对象没有原型。函数具有可用于链接的原型。希望这能有所帮助。
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发布于 2017-03-26 05:40:24
可以向像obj.something = function() {};这样的对象中添加方法。
至于方法链接,您希望在继承的函数中返回this。
所以像这样的东西会回答你的问题
function getObject(obj) {
obj.say = function() {
console.log(`Hello ${this.name}`);
return this;
}
obj.hi = function() {
console.log('hi');
return this;
}
return obj;
}
var newObj = getObject({});
newObj.say().hi();
// Helo A K
// hi此外,您还将obj.prototypes分配为等于一个类,而不是类原型。因此,在将来,如果您想要使一个原型与类原型相等,请使用obj.prototype = Object.create(anothingObj.prototype);
发布于 2017-03-26 05:41:51
您将显式地在对象.obj.prototype = undefined上添加一个prototype属性,当您使用新关键字调用它时,它只会向该属性添加一个空对象。因此,新的obj将是obj = {name:'james' , prototype: {}}。现在对象的prototype属性将指向F的prototype函数。正确的方法是通过Object.create。你可以这样模仿同样的行为
if(!Object.create){
Object.create = function(o) {
function F() {}
F.prototype = o ;
return new F();
};
}您可以查看MDN 文档以了解Object.create填充的详细说明。
https://stackoverflow.com/questions/43025343
复制相似问题