我刚开始接触JavaScript,我正试图把我的头脑围绕在原型继承上。似乎有多种方法可以达到相同的效果,所以我想看看是否有任何最佳实践或理由来以一种方式做事情。这就是我要说的:
// Method 1
function Rabbit() {
this.name = "Hoppy";
this.hop = function() {
console.log("I am hopping!");
}
}
// Method 2
function Rabbit() {}
Rabbit.prototype = {
name: "Hoppy",
hop: function() {
console.log("I am hopping!");
}
}
// Method 3
function Rabbit() {
this.name = "Hoppy";
}
Rabbit.prototype.hop = function() {
console.log("I am hopping!");
}
// Testing code (each method tested with others commented out)
var rabbit = new Rabbit();
console.log("rabbit.name = " + rabbit.name);
rabbit.hop();所有这些似乎都有相同的效果(除非我遗漏了什么)。那么,其中一种方法比另一种更受欢迎吗?你是怎么做到的?
https://stackoverflow.com/questions/8874115
复制相似问题