两者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
ofapply
方法将函数调用与其他对象绑定,以使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>