這些方法之間有任何技術差異嗎? [重復]

[英]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 联系我们: