引用类型之 Function

导读:Funtion 系列算是比较多而且加入新元素 Class,我们来一起学习吧。

Function 原型对象的属性

The Function prototype object is the intrinsic object %FunctionPrototype%. The Function prototype object is itself a built-in function object. When invoked, it accepts any arguments and returns undefined. It does not have a [[Construct]] internal method so it is not a constructor.
The value of the [[Prototype]] internal slot of the Function prototype object is the intrinsic object %ObjectPrototype%. The initial value of the [[Extensible]] internal slot of the Function prototype object is true.
The Function prototype object does not have a prototype property.
The value of the length property of the Function prototype object is 0.
The value of the name property of the Function prototype object is the empty String.

翻译如下:

Function 原型对象是内在对象 %FunctionPrototype%。Function 原型对象是内置的 function 对象。当它被调用时,它接受任意参数并返回 undefined。当然,它没有 [[Construct]] 内部方法,因此,他不是一个构造函数。
Function 原型对象 [[Prototype]] 的值指向的是 %ObjectPrototype%。 [[Extensible]] 也默认为 true
Function prototype 对象没有原型属性。
Function原型对象的 length 属性的值为 0。
Function原型对象的 name 属性的值是空字符串。


接下来我们讲讲 Function 原型方法,也是大家最熟悉那几个。

(1)Function.prototype.apply ( thisArg, argArray )、Function.prototype.call ( thisArg, ...args )

概述:这两个方法在指定 this 值和参数(参数以数组或类数组对象的形式存在)的情况下调用某个函数。

代码示例:

let name = function (...args) {
    return args;
};
let arg1 = name.apply(null,[1,2,3]);
let arg2 = name.call(null,1,2,3);
console.log(arg1);  // [1,2,3]
console.log(arg2);  // [1,2,3]

输出结果一致。这两个方法其实意思可以翻译为:例如,我这里借用 Math.Max.apply(null,[1,2,3]) 为例。将 Math.Max 这个方法借给 null 使用,传入 null 的参数是 [1,2,3]。这样就容易理解了吧。


(2)Function.prototype.bind ( thisArg, ...args )

概述:该方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this, 之后的一系列参数将会在传递的实参前传入作为它的参数。

该方法的目的就是做绑定,将要使用的对象上绑定你想要绑定的那个对象。

代码示例:

this.x = 9;
let module = {
    x: 81,
    getX: function() {
        return this.x; 
    }
};
module.getX(); // 返回 81
let retrieveX = module.getX;
retrieveX(); // 返回 9, 在这种情况下,"this" 指向全局作用域

// 创建一个新函数,将 "this" 绑定到 module对象
// 新手可能会被全局的 x 变量和 module 里的属性 x 所迷惑
let boundGetX = retrieveX.bind(module);
boundGetX(); // 返回 81

总结

惊喜,Function 原型对象上就只有这 3 个常用的方法。而它的原型上却有其他类型构造函数的方法。

你可能感兴趣的:(引用类型之 Function)