var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: test1.showname } test2.showname()
运算结果是windseek2,由于test2.showname=test1.showname所以test2.showname()=test1.showname();
test2.showname=
function () {
console.log(this.name);
}
test2.showname();对象时test2,所以this也指向test2 name自然也是test2.name windseek2
上面的代码也相当于这样写:
var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: function () { console.log(this.name); } } test2.showname()
运算结果是一样的
var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: function () { test1.showname(); } } test2.showname()
这时的运算结果应该是windseek1,由于test2.showname()执行其实是找到,test1.showname()执行,对象时test1,this指向test1,结果也就是test1.name也就是windseek1
var name="windseek"; var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: function () { var test=test1.showname; test(); } } test2.showname();
结果是windseek,因为test2.showname()执行时会找到test()执行,test=function () {console.log(this.name);},test前面没有任何对象,作用域就是全局的,this就是全局变量,this.name也就是windseek
上述代码可以解释成以下代码
var name="windseek"; var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: function () { var test=function () { console.log(this.name); }; test(); } } ( function () { var test=function () { console.log(this.name); }; test(); })();
写到这,感觉写代码像是在做数学题了,越来越有意思了
var name='windseek'; var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: function () { setTimeout(test1.showname,1000); } } test2.showname();
结果就是windseek其实,setTimeout等价于这种函数function(__callback){ __callback();} 最后执行的是callback
等价于这样写
var name='windseek'; var test1 = { name: 'windseek1', showname: function () { console.log(this.name); } } var test2 = { name:'windseek2', showname: function () { (function(__callback){ __callback(); })(test1.showname); } } test2.showname();
结果一样也是windseek,但是这个不会延迟,settimeout会延迟,setInterval也是一样的原理