复制代码 代码如下: <script type="text/javascript"> //在function中使用this function a() { if (this == window) { alert("this == window"); this.fieldA = "I"m a field"; this.methodA = function() { alert("I"m a function "); } } } a(); //如果不调用a方法,则里面定义的属性会取不到 alert(window.fieldA); methodA(); </script>
Demo 2 : 如果使用new的方式去实例化一个对象,则this不等于window对象,this指向function a的实例 复制代码 代码如下: <script type="text/javascript"> //在function中使用this之二 function a() { if (this == window) { alert("this == window"); } else { alert("this != window"); } this.fieldA = "I"m a field"; } var b = new a(); alert(b.fieldA); </script>
Demo 3 : 使用prototype扩展方法可以使用this获取到源对象的实例,私有字段无法通过原型链获取 复制代码 代码如下: <script type="text/javascript"> //在function中使用this之三 function a() { this.fieldA = "I"m a field"; var privateFieldA = "I"m a var"; } a.prototype.ExtendMethod = function(str) { alert(str + " : " + this.fieldA); alert(privateFieldA); //出错 }; var b = new a(); b.ExtendMethod("From prototype"); </script>
Demo 4 : 不管是直接引用function,还是实例化一个function,其返回的闭包函数里的this都是指向window 复制代码 代码如下: <script type="text/javascript"> //在function中使用this之四 function a() { alert(this == window); var that = this; var func = function() { alert(this == window); alert(that); }; return func; } var b = a(); b(); var c = new a(); c(); </script>