this / 'use strict' / call / %d/ 奇聞軼事

本章節記錄各式特殊作法。

this

取自Ching-Hsien Yeh的 超入門 JavaScript 教學 12 - 函式中的 this

 this字面意義為"這個" 把this想成函式裡的主角,總之,主要的功用就是用來代指該函數

var myShip = {
    x: 20,
    y: 45

};

var yourShip = {
    x: 150,
    y: 2048,
    getLocation: function() {
        console.log('x = ' + this.x + ', y = ' + this.y);
    }
};

function getShipLocation() {
    console.log('x = ' + this.x + ', y = ' + this.y);
}

function testThis() {
    console.log(this);
}

// 先看看yourShip的函式getLocation
//yourShip.getLocation();
//getShipLocation();

// 純粹測試this
//testThis();
//testThis.call(myShip);

// 看看getShipLocation如何找this
//var x = 768, y = 2048;
//getShipLocation();

// 再看一次yourShip
//yourShip.getLocation();
//myShip.getLocation();           
//yourShip.getLocation.call(myShip);
//yourShip.getLocation.call(yourShip);            

// 函式裡的this跟函式定義的位置無關
// 函式裡的this只跟函式被呼叫的時候誰在焦點有關係            
//getShipLocation();
//getShipLocation.call(myShip);
//getShipLocation.call(yourShip);
```

'use strict'

取自Ching-Hsien Yeh,同上

'use strict'將this限制在區域內,避免其上升到全域。

var 1={}
var 2={}
var 3={}

function testThis() {
    console.log(this);
}

//執行結果  (Object 1, Object 2, Object 3)

function testThis() {
    'use strict';
    console.log(this);
}

//執行結果  未定義


``````````````````

call

yourShip.getLocation.call(myShip);

//在yourShip物件找到getLocation這個函數,呼叫物件myShip作為該函數的對象。

results matching ""

    No results matching ""