JavaScript is referred to as JS. The original purpose of JS was to solve the interaction problem between the user and the server. It should be noted that JS is not an object-oriented language, but an object-based language that simulates an object-oriented language. So how do you create a JavaScript object?
Object: refers specifically to something in the natural world, with some characteristics (properties) and behaviors (methods). For example, the object Yao Ming has name, gender, height, and ball number. Teams and other characteristics, and can dribble, shoot, run, eat and other behaviors, then how do we use js to create objects?
The second type: Call the system constructor to create the object
var YaoMing = { name:"YaoMing", age:36, gender:"男", eat:function(){ console.log('吃臭豆腐'); }, read:(){ console.log('疯子在左天才在右'); } }
## The constructor creates the object
var per2=new Object();
per2.name="大蛇丸";
per2.age=30;
per2.sex="男";
per2.eat=function () {
console.log("吃榴莲");
};
per2.play=function () {
console.log("这个小蛇真好玩");
};
Now think about the third kind of custom constructor to create objects, what is its internal implementation process? ?
Take the above example, create an object
var per = new Person ("Hinata", 18, "Female"); When instantiating an object, the initialization assignment of attributes age, name, and gender is also completed. The internal process is as follows: Set this to the current object
* 3. Set the values of properties and methods
* 4. Return this object
第四种:工厂模式创建对象 "Xiao Ming",20);## Custom constructor function creates object: var per2=new Person("Xiaohong",20);
By comparing the above two methods of creating objects, we can draw the following conclusions:Creating objects in factory mode
1. The function name is lowercase, 2. The new keyword is used inside the function, 3. And there is a return value, 4. The object after new is the current object, 5. The object can be created by directly calling the function. # Customized constructor creation objects ## 1. The function name of the function name, 2. No use inside the function new keyword, 3. No return value, 4. this represents the current object, 5. Create an object through new.
The above is the detailed content of Examples explaining the four ways to create objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!