【问题标题】:JavaScript's anonymous objects prototypeJavaScript 的匿名对象原型
【发布时间】:2012-02-11 10:59:10
【问题描述】:

我学习 JavaScript 的“OOP”模型,并期待有关如何针对我遇到的一些问题编写代码的建议。 (稍后我将使用术语“实例”,但现在我知道 JavaScript 中没有实例。)考虑以下代码:

function Class1(){
   this.locvar1 = "locvar1";
   this.locvar2 = "locvar2";
}

function Class2(){
    this.set = function(){     
        this.locvar1 = "ch_locvar1";
    }
} 
Class2.prototype = new Class1;

//we'll get two instances from Class2
var x = new Class2();
x.set();  // we'll change the x's field with that (hoping that)

var y = new Class2();  // hoping that this will be a totally new instance,
                       // and the previous set() won't change it at all

好的,该代码将按照我想要的方式运行。我创建了两个新对象,以及它们的原型 在我调用 x.set() 之后还是一样。

x.locvar1's value: "ch_locvar1"
x.locvar2's value:  "locvar2"

y.locvar1's value:  "locvar1"
y.locvar2's value:  "locvar2"

their prototypes value: 
locvar1 : "locvar1", 
locvar2 : "locvar2"

问题来了,当我尝试在 Class1 的字段中使用更多对象时。

function Class1(){
   this.locvar1 = {a : "a"};
   this.locvar2 = "locvar2";
}

function Class2(){
    this.set = function(){     
        this.locvar1.a = "ch_locvar1";
    }
} 
Class2.prototype = new Class1;

var x = new Class2();
x.set();

var y = new Class2();

会出来的:

x.locvar1.a's value: "ch_locvar1"
x.locvar2's value:  "locvar2"

what's ok, but..:
y.locvar1.a's value:  "ch_locvar1"
y.locvar2's value:  "locvar2"

their prototypes value: 
locvar1.a : "ch_locvar1", 
locvar2 : "locvar2"

因此,似乎使用语句“this.locvar1.a”我全局更改了 {a : “a”} 对象的原型,而不是“this.locvar1”的本地实例......

我确定吗?我该如何解决这个问题?我试图改变“this.locvar1 = new {a : "a"};”因为这在我看来是合乎逻辑的,但结果是一样的。

【问题讨论】:

  • 在 javascript 中对象是通过引用传递的。这就是为什么在第二个示例中locvar1 发生了变化。
  • 我不确定你期望发生什么...?
  • CoffeeScript 似乎按照您的预期编译它:jsfiddle.net/nfJDk/14

标签: javascript oop scope closures prototype


【解决方案1】:

这将为您提供您所期望的原型继承:

function Class1(){
   this.locvar1 = {a : "a"};
   this.locvar2 = "locvar2";
}

function Class2(){
    this.__proto__ = new Class1()
    this.set = function(){     
        this.locvar1.a = "ch_locvar1";
    }
} 

var x = new Class2();
x.set();

var y = new Class2();

document.write(x.locvar1.a) // outputs 'ch_locvar1'
document.write('<br />')    
document.write(y.locvar1.a) // outputs 'a'

Class2 被实例化时,我已将原型对象设置为new Class1。正如其他人所解释的那样,它不会按照您的方式工作,因为两个对象都将引用相同的原型对象,并且 JavaScript 是通过引用传递的。

【讨论】:

  • 应避免使用__proto__,并且不适用于所有浏览器。
  • @Sarfraz 真的吗?我不知道。那怎么可能做我的sn-p跨浏览器呢?
  • 谢谢。然后是__proto__prototype
【解决方案2】:

this.locvar1 = new {a : "a"}; 错了,试试this.locvar1 = {a : "ch_locvar1"};

【讨论】:

  • 我不确定这如何回答这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
相关资源
最近更新 更多