function Benjamin(username, sex) {
this.username = username;
this.sex = sex;
}
var benjamin = new Benjamin("zuojj", "male");
//Outputs: Benjamin{sex: "male",username: "zuojj"}
console.log(benjamin);
var ben = Benjamin("zhangsan", "female");
//Outputs: undefined
console.log(ben);
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());