js中Object.create作用,什么时候用?和new是什么区别

javascript里类就是函数,声明一个类相当于声明一个类的构造函数。

//声明一个类
function Animal(name){
	this.name=name;
}
//创建一个对象
var cat=new Animal("Tom");

new创建一个对象,执行构造函数。

Object.create相当于创建一个对象,但是不执行构造函数。

var cat1=new Animal("Tom");
var cat2=Object.create(Animal.prototype);

console.log(cat1 instanceof Animal);//true
console.log(cat2 instanceof Animal);//true

那么通常在什么时候使用呢?

通常在类继承的时候使用。

javascript中通常继承的用法如下

//声明一个类
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

上面代码是继承的方式,其中创建了一个Animal对象,这个过程会执行Animal的构造函数。但是很多时候我们不想执行这段代码就想继承,于是我们就这样子

//声明一个类
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

通过这种方式就可以很好实现了

注意,代码中的

Cat.prototype.constructor=Cat;

是必要的,如果没有的话obj.constructor就会错误

猜你喜欢

转载自my.oschina.net/u/818899/blog/1606702