多重赋值的目的var x = this.x = function(){}?

时间:2013-03-13 15:23:28

标签: javascript design-patterns mootools variable-assignment

在Mootools中经常出现以下模式:

var x = this.x = function(){}

例如:

var typeOf = this.typeOf = function(item){ ...  

我了解function分配给xthis.x的多个作业结果。但我认为在全局范围内x隐含this.x,所以它似乎是多余的。这是一种优化技术,还是这种模式有其他目的?

2 个答案:

答案 0 :(得分:0)

如果此代码未在函数中执行,则这只是多余的。

如果它在函数中,则var是本地的,即使上下文(this)是全局的。

看看这个:

function a() {
   var x = 1;
   console.log(x)
}
function b() {
   console.log(x); // fails
}
a();
b();

如果您希望能够在x中直接使用a并在this.x中使用b,那么您需要进行双重分配:

 var x = this.x = 1;

我经常在大函数中使用这个模式,当我有一个变量时,我经常使用{而不是this.

答案 1 :(得分:0)

var x不等于this.x,var x是js类的变量private,this.x是公共属性,代码创建2种方式来调用函数 这是一个例子:

function exampleA() {
   this.x = 1;
   var x = 2;
   this.show = function () {
    alert("A.x:" + x);
    alert("A.this.x:" + this.x);
   };
}
function exampleB() {
   var x = this.x = 1;
   this.x   +=1; 
   this.show = function () {
    alert("B.x:" + x);
    alert("B.this.x:" + this.x);
   };
}
$(document).ready(

function () {
    var example1 = new exampleA();
    example1.show();
    var example1 = new exampleB();
    example1.show();
});
相关问题