这些方法之间有任何技术差异吗? [重复]

[英]Is there any technical difference between these methods? [duplicate]


This question already has an answer here:

这个问题在这里已有答案:

I have been trying to learn OO JS. I was playing with different patterns, wrote following example.

我一直在努力学习OO JS。我正在玩不同的模式,下面的例子写道。

var obj = function() {

    this.a= function() {
        return 'a';
    } 
}

obj.prototype.b = function() {
    return 'b';
} 


var instance = new obj();

console.log(instance.a());
console.log(instance.b()); 

Is there any difference here in function a and b?

这里的功能a和b有什么区别吗?

2 个解决方案

#1


1  

this.a will be a separate function for every object you create:

this.a将是您创建的每个对象的单独函数:

var obj = function() {    
    this.a= function() {
        return 'a';
    } 
}

obj.prototype.b = function() {
    return 'b';
} 

var instance1 = new obj();
var instance2 = new obj();

console.log(instance1 === instance2);     // false: different instances
console.log(instance1.a === instance2.a); // false: different functions (this.a)
console.log(instance1.b === instance2.b); // true:  obj.prototype.b

This means that this.a = function(){ ... } will consume memory for every instance, something you most likely want to avoid.

这意味着this.a = function(){...}将为每个实例消耗内存,这是您最可能想要避免的。

#2


1  

In your code, a is a function of the instance, whereas b is a function of the class.

在您的代码中,a是实例的函数,而b是类的函数。

In terms of them actually working, there isn't much different between them by themselves. However, let's say you put var test = 123; inside the obj function. a will be able to access it, but b will not.

就他们实际工作而言,他们之间并没有太大的不同。但是,假设你把var test = 123;在obj函数内部。 a将能够访问它,但b不会。

Additionally, you can overwrite instance.a with another function, and it will only affect the current instance.

此外,您可以使用其他函数覆盖instance.a,它只会影响当前实例。

On the other hand, a is a separate function object for each instance of the object. This could become a problem in terms of memory use if you have large numbers of instances.

另一方面,a是对象的每个实例的单独的函数对象。如果您有大量实例,这可能会成为内存使用方面的问题。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/09/11/c04a383beaa66c5137f57acc115dfe49.html



 
  © 2014-2022 ITdaan.com 联系我们: