函数与原型

匿名函数自调用bash

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

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

解析:ui

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。
复制代码

逗号表达式this

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

答案:11 21 10spa

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

逗号表达式code

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,25cdn

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

原型继承

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。

相关文章
相关标签/搜索