(function(){
var obj, sayHi;
obj = {};
sayHi = function(str){
console.log(str);
}
obj.sayHello = function(str1){
sayHi(str1);
}
obj.sayYo = function(str2){
console.log(str2);
}
window.obj = obj;
})()
obj.sayHello("hello world!"); // hello world!
obj.sayYo("yo, what's up?"); // yo, what's up?
A small problem I encountered myself, I don’t know if you have it. Recently, I like to write anonymous functions. When I first saw this, I habitually looked at it backwards and thought that it only exposed obj. Why is it in Can I execute sayHi when executing sayHello?
I thought I had seen the running mechanism of js before.
I don’t know if this is the case:
js should be pre-parsed when running
So before sayHello is executed, sayHello in the anonymous function should have become
obj.sayHello = function(str1){
function(str1){
console.log(str1);
};
};
I am not a professional, so I don’t know if this is the correct understanding?
This is a scope issue.
Just remember that the function has saved the scope when it is created. No matter where you call it later, the result will be the same. Just like your code, if you change it to this, the result will still be the same (for the sake of easy analysis below, give this immediately Call the function and give it a name, call it test):
Analysis, when the obj.sayHello function is created, it will save all current scopes:
At this time it is obvious that the sayHi function is in the scope of test, so this reference is directly saved in sayHello. Even if it is run in the global scope, the redefined sayHi in the global scope still cannot affect it, because it is from test Search in the function, you will understand if you look at the following example:
The scope of the foo function is foo itself + the global scope, so even if it is executed in the immediate execution function, the output value will not be 20, but only 10
This is not a good understanding, this should be a closure concept. http://www.ruanyifeng.com/blo...
When accessing a variable in a function, first check whether the function declares the variable. If not, go to the outer scope to find it. This is the case here, in the function (function(){})() I found sayHi, so I called it directly. If sayHi was not declared at this time, then continue to look for it in the outer layer of the function. If I find the overall situation directly, it still doesn't exist. Then there will be no more