将原型变量视为静态?

时间:2017-03-27 22:21:24

标签: javascript prototype

为什么将原型上的变量(和方法)视为静态是不正确的?我知道我们使用实例调用/更改它们,但如果我们更改它们,那么该更改将反映到所有实例,而不仅仅是实例本身。

function Calculator() {
    // constructor defined
    this.add = function(a, b) {
    return a+b;
  }
}

Calculator.prototype.staticvar = 'hello'

c1 = new Calculator();
c2 = new Calculator();

alert(c1.staticvar + ", " + c2.staticvar) // both hello

Calculator.prototype.staticvar = "hey!"

alert(c1.staticvar + ", " + c2.staticvar) // both change to hey!

事实上,根据定义,可以直接使用类访问静态变量,而无需创建实例成为原型对象上的变量/函数不被视为静态的主要原因吗?

2 个答案:

答案 0 :(得分:0)

他们不是静态的,他们继承。静态意味着它可以通过Calculator.staticvar访问,而不是calculatorInstance.staticvar。所以回答你的问题,是的,这与你不需要创建实例变量的事实有关。

事实上,在ES6 class中,在成员方法上使用static说明符时就是这种情况:



class Calculator {
  static get staticvar(){ return this._staticvar; }
  static set staticvar(value){ return this._staticvar = value; }
}

// "private" property, signified by leading underscore
Calculator._staticvar = 'hello';

console.log(Calculator.staticvar);

Calculator.staticvar = 'hey!';

console.log(Calculator.staticvar);




答案 1 :(得分:0)

与其他编程语言(如Java)不同,Javascript支持原型继承。函数原型在函数的所有实例之间共享。

我修改了代码以了解差异。

function Calculator() {
    // constructor defined
    this.add = function(a, b) {
        return a+b;
    }
}

Calculator.prototype.staticvar = 'hello';

c1 = new Calculator();
c2 = new Calculator();

alert(c1.staticvar + ", " + c2.staticvar) // both hello

c1.staticvar = "hey!";

alert(c1.staticvar + ", " + c2.staticvar) // alerts hey, hello

因此实例c1有自己的属性staticvar。并且c2没有自己的属性(staticvar)。因此c2.staticvar引用其原型对象。

因此,更改实例上的属性不会更改其他实例的属性值。

相关问题