Javascript this 关键字 详解(2)

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
实例一:

复制代码 代码如下:


function person() {
 return this.name;
}
//Function.prototype.bind
var per = person.bind({
 name: "zuojj"
});
console.log(per);
var obj = {
 name: "Ben",
 person: person,
 per: per
};
//Outputs: Ben, zuojj
console.log(obj.person(), obj.per());

实例二:

复制代码 代码如下:


this.x = 9;
var module = {
  x: 81,
  getX: function() { return this.x; }
};
//Outputs: 81
console.log(module.getX());
var getX = module.getX;
//Outputs: 9, because in this case, "this" refers to the global object
console.log(getX);
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
//Outputs: 81
console.log(boundGetX());

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgsgsw.html