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

Purpose of multiple assignment var x = this.x = function(){}?

本文关键字:function this var 赋值      更新时间:2023-09-26

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

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

例如:

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

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

只有当该代码不在函数中执行时,这才是多余的。

如果它是在一个函数中,var是局部的,即使上下文(this)是全局的。

看这个:

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

如果你想在a中直接使用x,在b中使用this.x,那么你需要双赋值:

 var x = this.x = 1;

我经常在大型函数中使用这种模式,当我有一个变量我使用很多,我更喜欢直接访问没有this.

var x不等于这个。X, var X是js类的私有变量。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();
});