this
每當被呼叫新的執行環境,就會被創造。
對類別語言而言 this 是什麼?
- this
- super
public class CashCard extends Card {
private String number;
private int balance;
private int bonus;
public CashCard(String number, int balance, int bonus) {
this.number = number;
this.balance = balance;
this.bonus = bonus;
}
public getBalance() {
return this.balance;
}
public static void main(String[] args) {
CashCard cashcard = new CashCard();
}
}
當不清楚 this 指向哪裡,你將會遇到什麼問題?
- 無意間宣告了全域變數
範例
範例一
// function statement
function a() {
this.myValue = 'hello';
console.log(this);
}
console.log('=== 1 ===');
a();
// function expressions
var b = function() {
this.myValue = 'hello';
console.log(this);
}
console.log('=== 2 ===');
b();
console.log(myValue);
範例二
var myObject = {
name: 'alincode',
log: function() {
this.name = 'daisy';
console.log(this); // ?
}
}
// 物件方法
myObject.log();
範例三
物件方法裡面宣告一個函式
var myObject = {
name: 'alincode',
log: function() {
var setName = function(newname) {
this.name = newname; // 這裡的 this 代表的是?
console.log(this);
}
setName('daisy');
}
}
myObject.log();
範例四
解決範例三的 pattern
var myObject = {
name: 'alincode',
log: function() {
var self = this;
var setName = function(newname) {
self.name = newname;
}
setName('daisy');
console.log(self);
}
}
myObject.log();