1. Simple object creation using object literals {}
This is the simplest, convenient, and quick way to create an object code as follows:
var obj = {};
obj.name = 'Outlaw maniac' // Add attributes and assign values
obj.age = 22
obj.sayHello = function(){
console.log('Hello')}Copy the code
Objects can be accessed using “.”
console.log(obj.name) // 'outlaw'
Copy the code
2. Use function to simulate class
- Creates an object equivalent to a new instance of a class (no argument constructor)
The code is as follows:
function Person(){}
var PersonOne = new Person(); // Define a function with the new keyword to "instantiate" as a class
personOne.name="Zhang";
personOne.hobby="coding";
personOne.work=function(){
alert(personOne.name+" is coding now...")
}
personOne.work();
Copy the code
- This can be implemented using a parameterized constructor, which is easier to define and more extensible (recommended)
The code is as follows:
function Pet(name,age,hobby){
this.name=name;// This scope: current object
this.age=age;
this.hobby=hobby;
this.eat=function(){
alert("My name is"+this.name+"I like it."+this.hobby+"Also a foodie.")}var maidou =new Pet("McDull".5."Sleep");// Instantiate/create the object
maidou.eat();// Call the function eat.
Copy the code
3, use factory to create (Object keyword)
The code is as follows:
var wcDog =new Object(a); wcDog.name="Prosperous wealth.";
wcDog.age=3;
wcDog.work=function(){
alert("I am"+wcDog.name+", woof woof......")
}
wcDog.work();
Copy the code
4, use the prototype object method prototype keyword
The code is as follows:
function Dog(){}
Dog.prototype.name="Prosperous wealth.";
Dog.prototype.age=3;
Dog.prototype.eat=function(){
alert(this.name+"A foodie.")}var wangcai =new Dog();
wangcai.eat();
Copy the code
5. Hybrid patterns (prototypes and constructors)
The code is as follows:
function Car(name,price){
this.name=name;
this.price=price;
}
Car.prototype.sell=function(){
alert("I am"+this.name+"I'm selling it now."+this.price+"Ten thousand dollars");
}
var camry =new Car(Camry.27);
camry.sell();
Copy the code
6. Dynamic prototyping (as a special case of hybrid mode)
The code is as follows:
function Car(name,price){
this.name=name;
this.price=price;
if(typeof Car.sell=="undefined"){
Car.prototype.sell=function(){
alert("I am"+this.name+"I'm selling it now."+this.price+"Ten thousand dollars");
}
Car.sell=true; }}var camry =new Car(Camry.27);
camry.sell();
Copy the code
These are the most common ways to create objects in javascript. If you have another idea, feel free to add…. in the comments section