组合已经具有自己属性的方法(使用原型属性)

Combine methods (using prototype property) that already have their own properties

本文关键字:属性 原型 方法 自己 组合      更新时间:2023-09-26

我有两个对象,humansam,每个有两个给定的属性

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()的谷歌结果第一页上的所有内容,但我从未见过正确类型的示例

编辑:我不想只是复制属性,因为我正在开发一款游戏,我不希望这些更改是永久性的。假设samhuman的原型,但在游戏的任何时候,他的原型都可能变成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