大佬教程收集整理的这篇文章主要介绍了JavaScript:函数字典:函数可以从其字典中引用函数吗?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的代码中,当从setTimeout调用somethingUseful.thisUsefulThing时,它是否可以引用somethingUseful.thatUsefulThing?
var somethingUseful = {
thisUsefulThing: function() {
this.thatUsefulThing();
},thatUsefulThing: function() {
console.log("I am useful!");
}
}
setTimeout(somethingUseful.thisUsefulThing,1000);
现在,我收到此错误:
Uncaught TypeError: Object [object global] has no method 'thatUsefulThing'
但是当你的代码当前运行时,’this’实际上并不是全局的,它是对所有直接后代本身有用的东西的引用.
当我使用文字对象时,我通常用名字而不是’this’来引用它们,所以在你的情况下,我会用somethingUseful.thatUsefulThing()替换’this.thatUsefulThing()’
为什么?因为无论如何它在全球范围内运作!
编辑:
正如plalx在他对我的回答的评论中指出的那样,实现这个类的最佳实践(使用示例类成员)将使用函数类/原型并看起来像这样:
function SomethingUseful () {
this.member = 'I am a member';
}
SomethingUseful.prototype.thisUsefulThing = function () {
this.thatUsefulThing();
}
SomethingUseful.prototype.thatUsefulThing = function () {
console.log('I am useful,and ' + this.member);
}
usefulObject = new SomethingUseful();
usefulObject.thisUsefulThing(); // logs fine with access to this.member
setInterval(usefulObject.thisUsefulThing.bind(usefulObject),1000); // has access to this.member through bind()
以上是大佬教程为你收集整理的JavaScript:函数字典:函数可以从其字典中引用函数吗?全部内容,希望文章能够帮你解决JavaScript:函数字典:函数可以从其字典中引用函数吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。