Javascript Object Oriented: how to traverse function inside an object?
let's say this is my code
var myObject = {
varA: true,
varB: false,
init: function() {
开发者_运维百科 //do something
},
doThis: function() {
//do this
function doThat(){
//do that
}
}
}
how do i call (if i can) the function doThat() from "outside" the object (like from a onclick on the page)? is it possible?
i'm working/hacking a piece of code left by a previsous developer and i dont want to rewrite everything from srcatch, so any good workaround is well accepted! thanks
You can't.
The function doThat is not exposed to any of the outer scopes. Unless you somehow change doThis to return a reference to doThat, there's no way of calling it besides declaring the function somewhere else.
There's no way to do this without modifying myObject; doThat is effectively a private function. There are several ways to work around this, for example making doThat a property of doThis. This is not recommended, but you did say you were hacking.
You can't. doThat is not a property of doThis or of myObject. You would have to modify the code to expose the enclosed doThat function.
var myObj = {
doThis: function() {
console.log("doing this");
return function doThat() { console.log("doing that"); };
}
};
The above would let you do:
myObj.doThis()(); // "doing this" / "doing that"
加载中,请稍侯......
精彩评论