【发布时间】:2014-12-27 22:36:25
【问题描述】:
我也对 JS 中的this 感到困惑,因为我知道如何在DOM 中使用this,但在OOP 中却无法理解
a = "uff";
function Class1() {
a = "";
}
function Class2() {
this.a = "";
}
well = new Class1();
oh = new Class2();
well.a = "bye";
oh.a = "ok";
console.log(well.a); // output: bye
console.log(oh.a); // output: ok
console.log(a); // output: ""
在上面的例子中是否使用this 不会影响代码那么我为什么要使用它以及为什么a 的最后一个值打印为空?我会非常感谢你们所有人。
【问题讨论】:
-
所有变量都是全局变量,这是不好的做法。
this在 JavaScript 中相当独特,我建议你先阅读一些互联网上的文章。这里有一个很受欢迎的问题可以开始stackoverflow.com/questions/3127429/javascript-this-keyword
标签: javascript oop this