In JavaScript , a class is a function, and declaring a class is equivalent to declaring a class constructor.
//声明一个类
function Animal(name){
this.name=name;
}
//创建一个对象
var cat=new Animal("Tom");
new creates an object and executes the constructor.
Object.create is equivalent to creating an object, but does not execute the constructor.
var cat1=new Animal("Tom");
var cat2=Object.create(Animal.prototype);
console.log(cat1 instanceof Animal);//true
console.log(cat2 instanceof Animal);//true
So when is it usually used?
Usually used in class inheritance .
The usual usage of inheritance in javascript is as follows
//声明一个类
function Animal(){
alert("这时候创建了一个Animal对象");
}
Animal.prototype.say=function(){
alert("啊");
};
//声明一个子类
function Cat(){
}
Cat.prototype=new Animal();//继承Animal
Cat.prototype.constructor=Cat;
Cat.prototype.say=function(){
alert("喵");
};
var cat=new Cat();
console.log(cat instanceof Cat);//true
console.log(cat instanceof Animal);//true
The above code is the way of inheritance, in which an Animal object is created, and this process will execute the constructor of Animal. But many times we don't want to execute this code and want to inherit, so we do it like this
//声明一个类
function Animal(){
alert("这时候创建了一个Animal对象");
}
Animal.prototype.say=function(){
alert("啊");
};
//声明一个子类
function Cat(){
}
Cat.prototype=Object.create(Animal.prototype);//继承Animal
Cat.prototype.constructor=Cat;
Cat.prototype.say=function(){
alert("喵");
};
var cat=new Cat();
console.log(cat instanceof Cat);//true
console.log(cat instanceof Animal);//true
In this way, it can be achieved very well
Note that in the code
Cat.prototype.constructor=Cat;
is necessary, if there is no obj.constructor will be wrong