Javascript学习笔记——8.7 函数属性、方法和构造函数

2018-07-05  本文已影响0人  IFELSE

函数是一个特殊的对象,所以可以有自己的属性和方法,甚至可以用Function()构造函数来创建新的函数

length

函数有只读的length属性,它代表函数定义的参数的个数。要与arguments.length区分开,后者是函数调用时传入参数的个数。

prototype

每个函数都包含不同的原型对象。当函数用作构造函数的时候,新创建的对象会从原型对象上继承属性。

call()和apply()

call和apply的作用相同,可以将对象引用为this,只是参数传入的方式不同。

    function add(c,d){
        return this.a + this.b + c + d;
    }

    var s = {a:1, b:2};
    console.log(add.call(s,3,4)); // 1+2+3+4 = 10
    console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14

bind

当在函数f()上调用bind()方法并传入一个对象o作为参数,这个方法将返回一个新的函数,调用新的函数会把原始函数f()方做o的方法来调用。

function add(){return this.x+this.y}
var o = {x:10,y:20}
var fun = add.bind(o)
fun() //30

toString

函数的toString方法大多返回函数的源码

//承接上面的代码
fun.toString()
"function () { [native code] }"
add.toString()
"function add(){return this.x+this.y}"

Function构造函数

除了使用function关键字定义,函数可以通过Function构造函数来定义
以下两种方式定义是等价的

var f1 = new function("x","y","return x*y")
var f2= function(x,y){return x*y}
var scope = 'global scope'
function consFun(){
    var scope = "local scope"
    return new Function("return scope")
}
consFun()() //"global scope"
上一篇 下一篇

猜你喜欢

热点阅读