`
lzj0470
  • 浏览: 1264448 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

两道JavaScript试题

    博客分类:
  • js
阅读更多

今天遇到两道JavaScript试题,都是与作用域有关,鄙人不才,两题皆负。

第一道大概是这样:

var Pet=function(){
    this.msg="Please show me delicious food...";
    this.shout=function(){
        console.log(this.msg);
    }
    this.waitAndShout=function(){
       //隔一段时间调用一次shout方法。
    }
}

以下是我给出的‘答案’(错误的,也是最上不了台面的)。

var Pet=function(){
    this.msg="Please show me delicious food...";
    this.shout=function(){
        console.log(this.msg);
    }
 
    this.waitAndShout=function(){
        var owner=this;
        setInterval(function(){
            this.shout();  
        },5000);
    }
}
new Pet().waitAndShout();

经测试发现setInterval方法下的function作用域指向发生了变化。于是改成一下代码(仍然是错误的)。

var Pet=function(){
    this.msg="Please show me delicious food...";
    this.shout=function(){
        console.log(this.msg);
    }
 
    this.waitAndShout=function(){
        var owner=this;
        setInterval(function(){
            owner.shout();
        },5000);
    }
}
new Dog().waitAndShout();

测试发现依旧存在问题:this.shout()方法中的this指针发生了变化,最终改成以下代码,终于运行正常。

var Pet=function(){
    this.msg="Please show me delicious food...";
    this.shout=function(){
        console.log(this.msg);
    }
 
    this.waitAndShout=function(){
        var owner=this;
        setInterval(function(){
            owner.shout.call(owner);
        },5000);
    }
}
new Pet().waitAndShout();

第二道题就比较诡异了

题目是写出输出结果:
var status="outer";
function showStatus(){
	var outerStatus=status;
	var status="inner";
	var innerStatus=status;
	alert('outerStatus: '+outerStatus);
	alert('innerStatus: '+innerStatus);
}
showStatus();

本以为第一个会输出outer,但是结果却是undefined。于是猜测JavaScript的变量声明都会被提前,并写下两个代码片段做验证:

片段1:
var status="outer";
function showStatus(){
	var outerStatus=status;
	var status="inner";
	var innerStatus=status;
 
    function status(){
	}
 
    alert('outerStatus: '+outerStatus);
	alert('innerStatus: '+innerStatus);
}
showStatus();

分解代码:

var outerStatus;
var status;
var innerStatus;
function status(){
}
outerStatus=status; //is a function
status="inner";
innerStatus=status; //innerStatus=="inner"
 
alert('outerStatus: '+outerStatus); //outerStatus: function(){}
alert('innerStatus: '+innerStatus);  //innerStatus: inner
片段2:
var status="outer";
function showStatus(){
	var outerStatus=status;
	var status="inner";
	var innerStatus=status;
 
    var status=function(){
    }
	alert(outerStatus);
    alert(innerStatus);
	alert(status)
}
showStatus();

分解代码:

var outerStatus;
var status;
var innerStatus;
var status;
outerStatus=status; //undefined
status="inner";
innerStatus=status; //innerStatus=="inner"
status=function(){}
alert('outerStatus: '+outerStatus); //undefined
alert('innerStatus: '+innerStatus);  //innerStatus: inner
alert('status: '+status);  //status: function(){}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics