var fun = 90;
(function () {
//对于fun,首先本范围内上部没有,那么就找本范围内的函数,如果函数没有就找外部,
//如果外部没有就undefinded,不会因为下部有但不是函数就选择下部的
console.log(fun); //输出的是fun2的那个
function fun() {
console.log('我是fun1方法');
}
function fun() {
console.log('我是fun2方法');
}
var fun = 3;
console.log(fun); //3
})()
var mmm = "da";
var obj = {
mmm: "xiao",
method: function () {
console.log(this.mmm); //xiao
function shakereturn() {
var mmm = "zuixiao";
console.log(this.mmm); //da
}
shakereturn();
(function shakereturn2() {
var mmm = "zuixiao2";
console.log(this.mmm); //da
})()
}
}
obj.method();
参数绑定
function attachfun(b, c) {
console.log(this.a + b + c);
}
attachfun(3, 4);//NaN
var bbb = { a: 20 };
attachfun.apply(bbb, [3, 4]);
attachfun.call(bbb, 3, 4);
var f_1 = attachfun.bind(bbb);
f_1(3, 4);
var f_2 = attachfun.bind(bbb, 3);
f_2(4);
//可以使用bind来设置this达到this暂存的效果。
var bar = {
name: "bar",
body: document.getElementsByTagName("body")[0],
greeting: function () {
console.log("Hi there, I'm " + this + ":" + this.name);
},
anotherMethod: function () {
this.body.addEventListener("click", (function () {
this.greeting();
}).bind(this));
}
};
bar.anotherMethod();
// Hi there, I'm [object Object]:bar