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);
When the constructor is called as a normal function, there is no return value, and this points to the global object. So how do we avoid problems caused by the lack of new keyword?
function Benjamin(username, sex) {
//Check whether "this" is a "Benjamin" object
if(this instanceof Benjamin) {
This.username = username;
This.sex = sex;
}else {
Return new Benjamin(username, sex);
}
}
var benjamin = new Benjamin("zuojj", "male");
//Outputs: Benjamin{sex: "male",username: "zuojj"}
console.log(benjamin);
var ben = Benjamin("zhangsan", "female");
//Outputs: Benjamin {username: "zhangsan", sex: "female"}
console.log(ben);
In the above example, we first check whether this is an instance of Benjamin. If not, use new to automatically call the constructor and instantiate it. This means that we no longer need to worry about missing the new keyword to instantiate the constructor. . Of course, we may develop a bad habit. What if we avoid this phenomenon? We can throw an error like this:
When we discussed the constructor above, we also discussed that when new is not applicable, this will point to the global object. Let’s take a look at two common examples of easy mistakes:
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.
Example 1:
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());
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn