Skip to content

Instantly share code, notes, and snippets.

@ryanlid
Last active November 5, 2016 00:47
Show Gist options
  • Save ryanlid/aa9ed16e878df35a92d7681ab70e2b5e to your computer and use it in GitHub Desktop.
Save ryanlid/aa9ed16e878df35a92d7681ab70e2b5e to your computer and use it in GitHub Desktop.
函数 Apply调用模式
// apply 方法让我们构建一个参数数组传递给调用函数。它也允许我们选择this的值,apply方法接收两个参数,第一个是要绑定给this的值,第2个是一个参数数组。
var add = function(a,b){
return a+b;
}
var array = [];
var sum =add.apply(null,array);
console.log(sum); // sum == 7
// apply 方法让我们构建一个参数数组传递给调用函数。它也允许我们选择this的值,apply方法接收两个参数,第一个是要绑定给this的值,第2个是一个参数数组。
// 创建一个构造器函数Quo。构造一个带 status 属性的对象
var Quo = function (string) {
this.status = string;
};
// 给 Quo 的所有实例提供一个名为你 get_status 的公共方法
Quo.prototype.get_status = function () {
return this.status;
};
// 构造一个 Quo 实例
var myQuo = new Quo("confused");
document.writeln(myQuo.get_status()); // "confused"
// 构造一个包含status成员的对象。
var statusObject = {
status: 'A-OK'
};
// statusObject并没有继承自 Que.prototype,但我们可以在 statusObject 上调用 get_status 方法,尽管 statusObject并没有一个名为get_status的方法。
var status = Quo.prototype.get_status.apply(statusObject);
console.log(status); // status 值为 'A-OK'。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment