函数与原型

匿名函数自调用

for(var i = 0 ; i < 5 ; i++){
    setTimeout((function(i){
        console.log(i);
    })(i),i*1000);
}
复制代码

答案:0,1,2,3,4

解析:

for(var i = 0 ; i < 5 ; i++){
    var fn = (function(i){
        console.log(i);
    })(i);
    setTimeout(fn,i*1000);
}
fn匿名函数自调用立即执行,所以先打印0,1,2,3,4。然后 函数没有返回值。所以
setTimeout(undefined,i*1000); 分别0s,1s,2s,3s,4s打印undefined。
复制代码

逗号表达式

var a = 10, b = 20;
function CommaTest(){
    return a++, b++, 10;
    }
var c = CommaTest();
alert(a); 
alert(b); 
alert(c); 
复制代码

答案:11 21 10

解析: a++ 先赋值再自增。不管怎样,最后的值都会加1.所以a为11,b为21。逗号表达式返回的都是最后一个值。所以结果为10。

逗号表达式

var out = 25,
inner = {
    out:20,
    func:function(){
        var out = 30;
        return this.out;
    }
};
console.log((inner.func, inner.func)());
console.log(inner.func());
console.log((inner.func)());
console.log((inner.func = inner.func)());
复制代码

答案:25,20,20,25

解析: (inner.func, inner.func)() 是进行逗号运算符,逗号运算符就是运算前一段表达式,且返回后一段表达式的结果。匿名函数的自调用,this指向的window。所以第一个this.out指向的全局的out 为25。 第二个和第三个都是方法调用。所以out为20。最后一个和第一个相同。等号运算符,返回的是结果inner.func = inner.func。即20。

原型

function superType(){
    this.property = true;
}
superType.prototype.getSuperValue = function(){   
    return this.property
}
function subType(){    //创建子构造函数
    this.subproperty = false
}
subType.prototype = new superType();  //继承
subType.prototype.getSubValue = function() {
    return this.subproperty
}
var instance = new subType() //实例
console.log(instance.getSuperValue())
复制代码

答案:true 解析:看图 instance通过__proto__.__proto__访问到getSuperValue();构造函数里的this.property为true。所以为true。

函数调用

function foo(x) {
    var tmp = 3;
    return function (y) {
        alert(x + y + (++tmp)); 4 2 
    }
}
var bar = foo(2); 
bar(10);  
复制代码

答案:16

解析:

bar(10) => function (y) {
        alert(x + y + (++tmp)); 4 2 
    }
所以y为10,因为x为2。 (++tmp)最后结果都会自增1.所以为 10+2+4 = 16。 
复制代码

函数声明与调用

var funce = [];
for(var i = 0; i < 3; i++){
    funce[i] = function(){
        console.log(i);  
    }
}
for(var j = 0; j < 3; j++){
    funce[j]();  
}
复制代码

答案:打印3次3

解析:

第一个for函数声明for循环结束i为3,但函数未调用。第二个for循环了3次分别调用了函数。所以打印了3次3。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值