函数Type——JS高程

2017-12-11  本文已影响0人  李奔

函数Type

函数是对象,函数名是指针。

函数作为参数:书中sort没有满足“负小前”的原则,改之

function createComparisonFunction(propertyName){
    return function(object1, object2){
        var value1 = object1[propertyName];
        var value2 = object2[propertyName];
        if(value1 > value2) return 1;
            else if (value1 < value2) return -1;
            else return 0;
    }
}
var data = [
    {name: "Zachary", age: 28}, 
    {name: 'Nicholas', age: 29}, 
    {name: "Sunhonglei", age: 43}
    ];
data.sort(createComparisonFunction('name'));
console.log(data)
data.sort(createComparisonFunction('age'));
console.log(data)
arguments的callee属性
function factorial(num){
    return num === 1 || num * factorial(num - 1)
}

function factorial2(num){
    return num === 1 || num * arguments.callee(num - 1)
}
console.log(factorial(5))   //120
console.log(factorial2(6))  //720
this--It is a reference to the context object that the function is operating on.比如浏览器的window,node.js的一大串对象。
color = "red";   //这里很有意思,一旦用let或var 定义,就输出undefined.
                 //但是chrome依然是red。可见node的this定义很奇怪
var o = { color: "blue" };
function sayColor(){
    console.log(this.color);
}
sayColor();          //red
o.sayColor = sayColor;
o.sayColor();        //blue

sayColor与o.sayColor两个指针指向同一个函数对象,但是execute in different contexts.
属性:caller

function outer(){
    inner()
    console.log(arguments.callee.caller)     //[Function]或者null
}
function inner(){
    console.log(inner.caller)       //[Function: outer]
}
outer()

严格模式下:TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.

属性与方法
+function inner(){
    console.log(inner.caller.toString())
}()

在node.js,最外层函数的caller即是:function (exports, require, module, __filename, __dirname) {}。哈哈,终于揪出了幕后凶手。在浏览器则是null.

上一篇 下一篇

猜你喜欢

热点阅读