组合已经具有自己属性的方法(使用原型属性)
Combine methods (using prototype property) that already have their own properties
我有两个对象,human和sam,每个有两个给定的属性
var human = {
legs: 2,
group: "mammal"
}
var sam = {
age: 23,
married: true
}
我是否可以将human对象附加到sam的原型上,以便将human的属性委派给sam,并且samobject保持不变
所需结果:console.log(sam.legs); //=> 2
我知道的一种方法(但我知道是"坏做法")是使用__proto__
属性:
var sam = {
age: 23,
married: true,
__proto__: human // *NOT IDEAL*
}
或
sam.__proto__ = human; // *NOT IDEAL*
我知道Object.create()
,但我不知道如何在不擦除sam变量中已经存储的所有内容的情况下实现它
var human = {
legs: 2,
group: "mammal"
}
var sam = {
age: 23,
married: true
}
sam = Object.create(human);
console.log(sam.age); //=> undefined
我知道我可以先将human对象附加到sam,然后将属性分配到sam:
var human = {
legs: 2,
group: "mammal"
}
var sam = Object.create(human);
sam.age = 23;
married: true;
但我问题的重点是,如果我使用prototype属性附加两个对象,它们已经有了自己的属性?我能以我不知道的方式使用Object.create()吗?
我一定已经阅读了object.create()
的谷歌结果第一页上的所有内容,但我从未见过正确类型的示例
编辑:我不想只是复制属性,因为我正在开发一款游戏,我不希望这些更改是永久性的。假设sam
有human
的原型,但在游戏的任何时候,他的原型都可能变成zombie
或其他什么。
您可以尝试构造函数,并将实例转换为其他实例。
定义以Human或Zombie作为构造函数参数的Human和Zombie类型。
function Human(obj){
obj = obj || {};
this.legs = obj.legs === 0 ? 0 :
obj.legs || 2;//defaults to 2
this.name = obj.name || 'nameless';
this.dead = false;
}
Human.prototype.saySomething = function(){
console.log('Hello, I''m ' + this.name);
};
//other functions of Human
function Zombie(obj){
//Zombie is a Human but it's dead
// re use Human constructor
Human.call(this,obj);
//re set the parameters that differ from Human
this.dead = true;
//add Zombie specific parameters if needed
}
//inherit prototype from Human
Zombie.prototype = Object.create(Human.prototype);
//repair constructor
Zombie.prototype.constructor=Zombie;
//override saySomething
Zombie.prototype.saySomething = function(){
console.log('Huarrrghhh');
}
var ben = new Human({name:'ben'});
ben.saySomething();
console.log(ben);
// now ben becomes a Zombie
ben = new Zombie(ben);
ben.saySomething();
console.log(ben);
你可以尝试不同的工厂功能,比如:
Human.toZombie = function(human){
return new Zombie(human);
}
var ben = new Human();
ben = Human.toZombie(ben);
有关构造函数函数和原型的详细信息:https://stackoverflow.com/a/16063711/1641941
相关文章:
- 如何从对象的原型方法访问JavaScript对象属性
- 附加到原型属性的Do函数没有闭包
- 日期原型属性
- 价值、原型和属性的差异
- 使用闭包创建原型中引用的私有属性
- 为什么属性存在于对象实例上,即使其原型发生了更改
- 为什么在原型中定义属性被视为反模式
- JS构造函数的原型属性与其原型之间的区别
- 为什么函数对象的实例没有继承函数原型属性
- 组件是HTML5的属性还是原型.js的东西
- 为什么浏览器显示原型属性不同
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- Javascript设置&阴影属性(原型链)
- 高图表热图 未捕获类型错误:无法读取未定义的属性“原型”
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 未捕获的类型错误:无法读取未定义的属性“原型”
- 如何在DOM object的构造函数中添加属性.原型在Internet Explorer<=IE8
- 扩展类不能读取未定义的属性原型
- 未捕获的类型错误:无法读取未定义的 sails.io.js 的属性“原型”
- 升级到量角器4后无法读取未定义的属性“原型”