Prototypal Inheritance最佳实践? [英] Prototypal Inheritance best practices?

查看:59
本文介绍了Prototypal Inheritance最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入JavaScript,我正试图围绕原型继承。似乎有多种方法可以达到同样的效果,所以我想看看是否有任何最佳实践或理由以一种方式做事。以下是我所说的:

I'm just getting into JavaScript and I'm trying to wrap my head around prototypal inheritance. It appears that there's multiple ways to achieve the same effect, so I wanted to see if there is any best practices or reasons to do things one way over the other. Here's what I'm talking about:

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

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

All of these appear to have the same effect individually (unless I'm missing something). So is one method preferred over the other? How do you do it?

推荐答案

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

When you put a method on the prototype, every instance object shares the same reference to the method. If you have 10 instances, there is 1 copy of the method.

当您执行示例1中所做的操作时,每个实例对象都有自己的相同方法版本,所以如果你创建了10个对象,那么就会运行10个代码副本。

When you do what you did in example 1, every instance object has its own version of the same method, so if you create 10 of your objects, there are 10 copies of the code running around.

使用原型是有效的,因为javascript具有与函数执行相关联的机制实例,即它设置这个属性来执行函数。

Using the prototype works because javascript has machinery for associated a function execution with a instance, i.e. it sets the this property for the execution of the function.

所以使用原型是首选因为它占用的空间更少(当然,除非您想要的是这样)。

So using the prototype is highly preferred since it uses less space (unless of course, that is what you want).

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

In method 2, you are setting the prototype by setting it equal to an object literal. Note that here you are setting a property, which I think you don't intend to do, since all instances will get the same property.

在方法3中,您是一次建立原型一个任务。

In Method 3, you are building the prototype one assignment at a time.

我更喜欢方法3。即在我的构造函数中,我设置了我的属性值

I prefer method 3 for all things. i.e. In my constructor I set my property values

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.

这篇关于Prototypal Inheritance最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆