最近遇到了一道 javascript 考题,内容如下:
尝试实现注释部分的 javascript 代码,可在其他任何地方添加更多
代码(如不能实现,说明一下不能实现的原因):
var obj = function(msg){
this.msg = msg;
this.shout = function(){
alert(this.msg);
}
this.waitandshout = function(){
// 隔五秒钟后执行上面的 shout 方法
}
}
var testobj = new obj("hello,world!");
testobj.shout();坦白的说,之前我并没有在 javascript 类中使用 settimeout/setinterval 的经验,所以开始就很草率的认为这是无法实现的。但是经过深思熟虑以后发现是可以实现的。退一步说,隔五秒执行某段语句是非常容易实现的。比如不考虑别的因素,题目中的函数是可以这样写:
this.waitandshout = function(){
settimeout('this.shout()', 5000);
}在运行以后,谁都会意识到 this 这个变量是无法找到的。但是这是为什么呢,很快就可以意识到,其实 settimeout/setinterval 是 window 对象的一个方法,所以也可以写成 window.settimeout/window.setinterval,那么上述的 this.shout() 就非常可以容易理解为什么不能执行了,因为它实际上调用的是 window.shout() 。
知道了原因以后解决起来就非常的容易了,只要将对象绑定到 window 对象下就可以(我对 javascript 有趣的对象机制感到兴奋)。那么,上述的函数再做一个小的修改:
this.waitandshout = function() {
window.obj = this;
settimeout('obj.shout()', 5000);
}这样就可以了。实际上
settimeout('obj.shout()', 5000);等价于
window.settimeout('window.obj.shout()', 5000);另外,之前我也想到将对象保存为数组,然后引用调用,代码如下:
function objectclass (property) {
this.property = property;
this.id = objectclass.cnt;
objectclass.objects[objectclass.cnt++] = this;
this.method = objectclass_method;
}
objectclass.cnt = 0;
objectclass.objects = new array();
function objectclass_method () {
settimeout('objectclass.objects[' + this.id + '].method();', 5000);
}
var obj1 = new objectclass('feelinglucky');
obj1.method();不过个人感觉还是上述第一种方法清晰得多。
后记,javascript 看来的确还是很多需要谨慎对待的地方,尤其是对象机制。就犹如我之前所说的,javascript 并不比其他语言要复杂,但是它也没有你想象中的简单。
ps:完成这道题目以后, google 发现其他的兄弟早已经解决了此类的问题,比如这里还有这里,可以对比参考一下。
--------------------------------------------------------------------------------
更新,感谢 sheneyan 兄弟的提醒,还有另外的一个办法就是通过 closure(闭包) 来实现,代码如下:
var obj = function(msg){
this.msg = msg;
this.shout = function() {
alert(this.msg);
this.waitandshout();
}
var _self = this;
this.waitandshout = function() {
settimeout(function(){_self.shout()}, 5000);
}
}
var testobj = new obj("hello,world!");
testobj.shout();看来这道题已经不能再害人了 :^)
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号