call()
它可以用来调用所有者对象作为参数的方法。通过call()能够使用属于另一个对象的方法。
var person = { fullName: function() { return this.firstName + " " + this.lastName; } } var person1 = { firstName:"Bill", lastName: "Gates", } var person2 = { firstName:"Steve", lastName: "Jobs", } person.fullName.call(person1); // 将返回 "Bill Gates"
call() 方法可接受参数:
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"Bill", lastName: "Gates" } person.fullName.call(person1, "Seattle", "USA");
apply()
call()和apply()之间的区别:
call()方法分别接受参数。
apply()方法接受数组形式的参数。
如果要使用数组而不是参数列表,则 apply() 方法非常方便。
带参数的apply()方法:
接受数组中的参数。
var person = { fullName: function(city, country) { return this.firstName + " " + this.lastName + "," + city + "," + country; } } var person1 = { firstName:"John", lastName: "Doe" } person.fullName.apply(person1, ["Oslo", "Norway"]);
bind() //不太明白
bind()创建的是一个新的函数(称为绑定函数),与被调用函数有相同的函数体,当目标函数被调用时this的值绑定到 bind()的第一个参数上.