Jan*_*anD 2 javascript oop binding
在属于javascript对象的JavaScript函数中,我想使用另一个对象的属性值:
var firstObject={
says:"something"
}
var secondObject={
speak:function(){console.log(this.saysToo)},
saysToo:firstObject.says
}
secondObject.speak();
Run Code Online (Sandbox Code Playgroud)
在调试器中检查“ secondObject”时,“ saysToo”具有正确的值。但是,如果我尝试通过“ this.saysToo”访问它,则它是未定义的。
如何从第二个对象中访问第一个对象的属性?
这两个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>
Run Code Online (Sandbox Code Playgroud)
可以使用callof 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>
Run Code Online (Sandbox Code Playgroud)