扫码关注官方订阅号
这段代码js是如何解析的?
认证0级讲师
当你执行object.getNameFunc()时,返回的是一个匿名函数:
function(){ return this.name; }
当你调用该匿名函数时,这是的this指向的是window,因为js中所有匿名函数的this都执行window,所以最好返回的值是'The Window'。如果你想让当前匿名函数返回当前object中的name有两种方法:
1:为object方法中指定一个that变量,让that指向this。在对象方法中的this指向的都是当前对象。
getNameFunc: function() { var that = this; return function() { return that.name; } }
2:使用call来调用该匿名函数,改变this的指向。
object.getNameFunc().call(object);
这个就是经典的this问题,请Google下js this或在SF里面搜下js this即可,比如参考下面两篇文章:
this
js this
http://www.ruanyifeng.com/blo...
http://web.jobbole.com/85198/
var name; name = 'The Window'; var object = {}; object.name = 'My Object'; object.getNameFunc = function(){ console.log(this.name); //My Object 'My Object'; return function(){ return this.name; //window.name 'The Window'; } }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
当你执行object.getNameFunc()时,返回的是一个匿名函数:
当你调用该匿名函数时,这是的this指向的是window,因为js中所有匿名函数的this都执行window,所以最好返回的值是'The Window'。如果你想让当前匿名函数返回当前object中的name有两种方法:
1:为object方法中指定一个that变量,让that指向this。在对象方法中的this指向的都是当前对象。
2:使用call来调用该匿名函数,改变this的指向。
这个就是经典的
this问题,请Google下js this或在SF里面搜下js this即可,比如参考下面两篇文章:http://www.ruanyifeng.com/blo...
http://web.jobbole.com/85198/