Demo 1:
function Person(){ this.name = 'hjzgg'; this.age = 24; this.show = function(){ alert(name + " " + age); } } var p = new Person(); p.show();
錯誤:name 和 age都沒有定義。
Demo 2:
function Person(){ this.name = 'hjzgg'; this.age = 24; this.show = function(){ alert(this.name + " " + this.age); } } var p = new Person(); p.show();
正確。
Demo 3:
function Person(){ this.name = 'hjzgg'; this.age = 24; this.show = function(){ alert(this.name + " " + this.age); } } var p = new Person(); p.show.call({});
錯誤:name 和 age 未定義。
Demo 4:
function Person(){ this.name = 'hjzgg'; this.age = 24; var self = this; this.show = function(){ alert(self.name + " " + self.age); } } var p = new Person(); p.show.call({});
通過 var self = this,正確。
Demo 5:
function Person(){ this.sayHello = function(){ alert('hello world!'); } this.show = function(){ sayHello(); } } var p = new Person(); p.show();
錯誤:sayHello未定義。
Demo 6:
function Person(){ var sayHello = function(){ alert('hello world!'); } this.show = function(){ sayHello(); } } var p = new Person(); p.show();
正確。
結論:
每個函數都有屬於自己的this對象,這個this對象是在運行時基於函數的執行環境綁定的,即在全局對象中,this指向的是window對象;在自定義函數中,this對象指向的是調用這個函數的對象,也就是說,this指向的是調用執行環境的那個對象。如果是在函數嵌套環境中,this指代的是調用外部函數或者內部函數的執行環境的對象。
那么這里可能又會出現新的疑問:為什么self.name 和 self.age是正確的呢?
其實這又涉及到另一個話題:實例成員與局部成員。我們創建構造函數的意義就是要用它來創建實例,那么所有屬於實例的成員都需要用this來定義;而只有那些不屬於實例的成員才不會用this定義;當然,用this定義了方法以后,在函數作用域內部要調用此方法時,就需要加上this了。
Demo 7:
var person = { name : 'hjzgg', age : 24, show : function(){ alert(name + " " + age); } } person.show();
錯誤:name 和 age未定義。
Demo 8:
var person = { name : 'hjzgg', age : 24, show : function(){ alert(this.name + " " + this.age); } } person.show();
正確。
Demo 9:
var person = { name : 'hjzgg', age : 24, show : function(){ alert(this.name + " " + this.age); } } person.show.call({});
錯誤:name 和 age 未定義。
Demo 10:
var person = { name : 'hjzgg', age : 24, show : function(){ alert(person.name + " " + person.age); } } person.show.call({});
正確。