函数Type——JS高程

函数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.

属性与方法
  • The length property indicates the number of named arguments that the function expects
  • prototype属性指向原型对象,not enumerable and so will not be found using for-in.
  • apply()和call()改变函数的this指向的对象
  • The bind() method creates a new function instance whose this value is bound to the value that was passed into bind() .
  • toString()返回整个函数;valueOf()只返回函数说明
  • caller
+function inner(){
    console.log(inner.caller.toString())
}()

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

推荐阅读更多精彩内容