这些方法之间是否存在技术上的差异?

3

我一直在努力学习面向对象的JavaScript编程。我尝试了不同的模式,并写出了以下示例。

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

这里的函数a和b有什么区别吗?

1
(new obj).a !== (new obj).a(new obj).b === (new obj).b - Bergi
2个回答

1
"

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.a = function(){ ... }

1
在您的代码中,a 是实例的一个函数,而 b 是类的一个函数。
就它们本身而言,在它们实际工作方面并没有太大的区别。然而,假设您将 var test = 123; 放在 obj 函数内部,那么 a 将能够访问它,但 b 将不能。
此外,您可以用另一个函数覆盖 instance.a,它只会影响当前实例。
另一方面,a 是对象每个实例的单独函数对象。如果您有大量实例,这可能会成为内存使用方面的问题。

即使这个解释有一定的正确性,但是在JavaScript中并没有类。 - user1047100
2
只需将其标记为重复即可,而不是提供不完美的答案 :-) - Bergi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接