在JavaScript函数中,属于javascript对象,我想使用另一个对象属性的值:
var firstObject={
says:"something"
}
var secondObject={
speak:function(){console.log(this.saysToo)},
saysToo:firstObject.says
}
secondObject.speak();
在我检查调试器中的“secondObject”时,“sayToo”具有正确的值。但是,如果我尝试通过“this.saysToo”访问它,则它是未定义的。
如何从第二个对象中访问第一个对象的属性?
答案 0 :(得分:3)
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>