gpt4 book ai didi

javascript - 如何将原型(prototype)附加到 JS 中的对象文字

转载 作者:行者123 更新时间:2023-11-29 22:22:51 25 4
gpt4 key购买 nike

我试图理解 JavaScript 的原型(prototype)性质,并且我试图在不使用类构造函数的情况下创建对象继承。

如果 Cat 和 Dog 都是三个对象字面量,我如何将原型(prototype)链从 Animals 附加到它们?

此外,是否有一种方法可以执行 Object.create 并以文字形式添加更多属性(如 myCat)。

我添加了下面的代码并粘贴到 bin http://jsbin.com/eqigox/edit#javascript

var Animal = {
name : null,
hairColor : null,
legs : 4,

getName : function() {
return this.name;
},
getColor : function() {
console.log("The hair color is " + this.hairColor);
}
};

/* Somehow Dog extends Animal */

var Dog = {
bark : function() {
console.log("Woof! My name is ");
}
};

/* Somehow Cat Extends Animal */

var Cat = {
getName : function() {
return this.name;
},

meow : function() {
console.log("Meow! My name is " + this.name);
}
};


/* myDog extends Dog */

var myDog = Object.create(Dog);

/* Adding in with dot notation */
myDog.name = "Remi";
myDog.hairColor = "Brown";
myDog.fetch = function() {
console.log("He runs and brings back it back");
};


/* This would be nice to add properties in litteral form */
var myCat = Object.create(Cat, {
name : "Fluffy",
hairColor : "white",
legs : 3, //bad accident!
chaseBall : function(){
console.log("It chases a ball");
}

});

myDog.getColor();

最佳答案

您可以使用 Object.create 将您定义的对象用作原型(prototype)。例如:

var Dog = Object.create(Animal, {
bark : {
value: function() {
console.log("Woof! My name is " + this.name);
}
}
});

现在您可以创建一个新的 Dog 对象:

var myDog = Object.create(Dog);
myDog.bark(); // 'Woof! My name is null'
myDog.getColor(); // 'The hair color is null'

示例:http://jsfiddle.net/5Q3W7/1/

或者,如果您在没有 Object.create 的情况下工作,您可以使用构造函数:

function Animal() {
this.name = null;
this.hairColor = null;
this.legs = 4;
};

Animal.prototype = {
getName : function() {
return this.name;
},
getColor : function() {
console.log("The hair color is " + this.hairColor);
}
}

function Dog() {
}

Dog.prototype = new Animal;
Dog.prototype.bark = function() {
console.log("Woof! My name is " + this.name);
};

示例:http://jsfiddle.net/5Q3W7/2/

有关 Object.create 的更多信息:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create/

有关构造函数和原型(prototype)链的更多信息: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor

https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_and_the_prototype_chain

关于javascript - 如何将原型(prototype)附加到 JS 中的对象文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11388181/

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