length
形参的个数
function func1() {}function func2(a, b) {}console.log(func1.length) // 0console.log(func2.length) // 2
方法
apply() 调用一个具有给定this 值的函数,以及作为一个数组(或类数组)提供的参数
func.apply(thisArg, [argsArray])// 用apply将数组添加到另一个数组let array = ['a', 'b']let elements = [0, 1, 2]array.push.apply(array, elements)console.log(array) // ['a', 'b', 0, 1, 2]// 使用apply和内置函数 【找到数组中的最大/最小值】let max = Math.max.apply(null, elements)let min = Math.min.apply(null, elements)console.log(max) // 0console.log(min) // 2
call() 使用一个指定的this值和单独给出的一个或多个参数来调用一个函数
function Product(name, price) {this.name = namethis.price = price}function Food(name, price) {Product.call(this, name, price)this.category = 'food'}let cheese = new Food('feta', 5) // {name: 'feta', price: 5, category: 'food'}
// 调用匿名函数var animals = [{ species: 'Lion', name: 'King' },{ species: 'Whale', name: 'Fail' }];for (var i = 0; i < animals.length; i++) {(function(i) {this.print = function() {console.log('#' + i + ' ' + this.species + ': ' + this.name)}this.print()}).call(animals[i], i)}
// 不指定第一个参数, this 就绑定全局对象var sData = 'Wisen'function display() {console.log('sData value is %s ', this.sData)}display.call(); // sData value is Wisen
bind() 绑定方法
// 创建绑定函数this.x = 9let module = {x: 81,getX: function() {return this.x}}module.getX() // 81let retrieveX = module.getXretrieveX(); // 9let boundGetX = retrieveX.bind(module)boundGetX(); // 81
// 偏函数 =》 拥有预设的初始参数function list() {return Array.prototype.slice.call(arguments)}function addArguments(arg1, arg2) {return arg1 + arg2}let leadList = list.bind(null, 37)let leadAdd = addArguments(null, 37)leadList() // [37]leadList(1, 2, 3) [37, 1, 2, 3]leadAdd(5) // 37 + 5 = 42leadAdd(5, 10) // 37 + 5 = 42
// 配合setTimeout使用 this => window 对象function LateBloomer() {this.petalCount = Math.ceil(Math.random() * 12) + 1}LateBloomer.prototype.bloom = function() {window.setTimeout(this.declare.bind(this), 1000)}LateBloomer.prototype.declare = function() {console.log('I am a beautiful flower with ' + this.petalCount + ' petals!')}let flower = new LateBloomer()flower.bloom() // 一秒钟后,调用‘declare’ 方法
// 绑定构造函数function Point(x, y) {this.x = xthis.y = y}Point.prototype.toString = function() {return this.x + ' ' + this.y}let p = new Point(1, 2)p.toString() // '1, 2'let emptyObj = {}let YaxisPoint = Point.bind(null, 0)let axisPoint = new YaxisPoint(5)axisPoint.toString()
