firstObject
和secondObject
是單獨的對象。關鍵字this
引用其執行上下文的對象。
<script>
var firstObject = {
says: "something",
test: function() {
//this == firstObject
console.log(this == firstObject); //shows: true
}
}
var secondObject = {
speak: function() {
//this == secondObject
console.log(this.saysToo);
},
saysToo: firstObject.says,
test: function() {
//this == secondObject
console.log(this == secondObject); //shows: true
console.log(this == firstObject); //shows: false
},
}
secondObject.speak();
//this == window
console.log(this===window); //shows: true
console.log(typeof this.saysToo); //shows: undefined
//because "this.saysToo" is same as "window.saysToo" in this (global) context
</script>
函數調用可以使用方法call
的apply
其他目的是使this
在於函數表現得像另一個對象的約束。
<script>
var firstObject = {
says: "something",
saysToo: "other"
}
var secondObject = {
speak: function() {
console.log(this.saysToo);
},
saysToo: firstObject.says
}
secondObject.speak(); //shows: "something"
//bind with "firstObject"
secondObject.speak.call(firstObject); //shows: "other"
</script>
來源
2012-10-28 23:05:54
Jay
我沒有得到undefined。你使用什麼瀏覽器?另外,請發佈輸出。 – jmort253
[適用於我。](http://jsfiddle.net/csBXN/) –
這是您真實的實際代碼嗎? – jmort253