如果你使用成员函数,会有很大的不同。局部变量是立即可见的,但属性不是。他们需要this。但是——这是最大的区别——有时成员函数根本看不到它们自己的属性。一些标准代码,带有基本构造函数:
function Cat() { // constructor with a var and property
var a="local a"; // variable
this.b="local b"; // property
this.showBad = function() { return a+", "+b; } // local a, but searches for b in global
this.showGood = function() { return a+", "+this.b; } // local a and b (but has a bug, explained below)
}
var c1=new Cat(); // using the constructor
var a="GLOBAL A", b="GLOBAL B"; // if we can't see c1's locals, we get these
console.log(c1.showBad()); // local a, GLOBAL B // oops on B
console.log(c1.showGood()); // local a, local b // works fine, using "this"
到目前为止,没什么大不了的。属性需要this,而变量不需要(实际上他们没有)。小东西。但是this 并不总是有效。在 javascript 成员函数中,this 可以是任何东西。如果您习惯于 OOP 语言,那似乎是错误的。这里我们调用c1.showGood 并将this 设置为全局范围:
var sGood=c1.showGood; // sGood is the function "c1.showGood"
console.log(sGood()); // local a, GLOBAL B // Argg. this.b didn't work!
这似乎是假的,但这样的事情可能会发生。由于这两件事(变量总是有效的,我们需要一种可靠的方法来始终查看我们的属性),一个标准的技巧是在构造过程中将你的this 锁定在一个变量中。它很好地显示了 var/property 的差异:
function Cat() { // constructor with a var and property
var self = this; // self is our permanent, always visible link to this Cat
this.a="local a";
this.b="local b";
this.showGood = function() { return self.a+", "+self.b; }
}
self 是一个变量,所以我们的showGood 总能找到我们的。同时a和b只能通过链接找到,self完成。