JavaScirpt(JS)的this細究
阿新 • • 發佈:2018-11-11
一、js中function的不同形態
js中類和函式都要通過function關鍵字來構建。
1、js中當函式名大寫時,一般是當作類來處理
function Foo(name, age) { this.name = name; this.age = age; this.getName = function () { console.log(this.name) } } obj = new Foo('文州', 19); // 例項化一個物件 obj.getName(); // 輸出:文州
2、js中函式名小寫,當做函式來處理
function test() { console.log(this); } // 等同於window.test,因此這裡的this代指的是window test(); // 輸出:Window
3、自執行函式,同上面等價
自執行函式,同上面等價,this也是代指的window。
(function () { console.log(this); // 輸出:Window })()
二、複合案例
1、類和函式結合案例
var name = '景女神'; function Foo(name, age) { this.name = name; this.age = age; this.getName = function () { console.log(this.name); // 文州 (function () { console.log(this.name); // 景女神(列印的外部全域性變數) })() } } obj = new Foo('文州', 19); obj.getName(); // 文州 景女神
生成物件後,物件執行getName方法,此時this.name是輸出的當前物件的name,因此是輸出文州。隨後再執行自執行函式,這裡的this指代的是window物件,獲取全域性name變數,因此輸出景女神。
2、讓上例中自執行函式也列印物件的name
var name = '景女神'; function Foo(name, age) { this.name = name; this.age = age; this.getName = function () { console.log(this.name); // 文州 var that = this; (function () { console.log(that.name); // 文州(列印的外部全域性變數) })() } } obj = new Foo('文州', 19); obj.getName(); // 文州 文州
3、自動例項化案例
obj = { name: '文州', age: 19, getName:function () { console.log(this.name); // 文州 var that = this; (function () { console.log(that.name); // 文州 })() } } obj.getName();