gpt4 book ai didi

javascript - 原型(prototype)继承最佳实践?

转载 作者:行者123 更新时间:2023-12-03 07:59:40 26 4
gpt4 key购买 nike

我刚开始接触 JavaScript,我正试图围绕原型(prototype)继承。似乎有多种方法可以达到相同的效果,所以我想看看是否有任何最佳实践或理由以一种方式而不是另一种方式做事。这就是我所说的:

// 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();

所有这些似乎单独具有相同的效果(除非我遗漏了什么)。那么一种方法优于另一种方法吗?你怎么做呢?

最佳答案

当您在原型(prototype)上放置一个方法时,每个实例对象都共享对该方法的相同引用。如果您有 10 个实例,则该方法有 1 个副本。

当您执行示例 1 中的操作时,每个实例对象都有自己的相同方法版本,因此如果您创建 10 个对象,则有 10 个代码副本在运行。

使用原型(prototype)是可行的,因为 javascript 具有将函数执行与实例相关联的机制,即它设置了 this用于执行函数的属性。

所以使用原型(prototype)是非常受欢迎的,因为它使用的空间更少(当然,除非你想要这样)。

在方法 2 中,您通过将原型(prototype)设置为对象文字来设置原型(prototype)。请注意,您在这里设置了一个属性,我认为您不打算这样做,因为所有实例都将获得相同的属性。

在方法 3 中,您一次构建一个分配的原型(prototype)。

对于所有事情,我更喜欢方法3。即在我的构造函数中,我设置了我的属性值

myObj = function(p1){
this.p1; // every instance will probably have its own value anyway.
}

myObj.prototype.method1 = function(){..} // all instances share the same method, but when invoked **this** has the right scope.

关于javascript - 原型(prototype)继承最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874115/

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