一、创建对象的三种方式:
1、字面量:
var o1 = {name: "o1"}
var o2 = new Object({name: "o2"})
2、构造函数:
var Person = function(name){ this.name = name }
var p = new Person("tom");
console.log(p.name); //tom
3、Object.create:
var person = {name: "mike"}
var child = Object.create(person);
console.log(child.name); //mike
新创建的对象child的原型就是person,同时child也拥有了属性name。
二、JS实现继承的几种方式
1、借用构造函数实现继承
function Parent(){
this.name='parent'
}
function Child(){
Parent1.call(this);
this.type='child'
}
var child=new Child();
child.name; //parent
child.type; //child
【缺点】Child无法继承Parent的原型对象,并没有真正的实现继承(部分继承)。
2、借用原型链实现继承
function Parent(){
this.name='parent';
this.play=[1,2,3];
}
function Child(){
this.type='child';
}
Child.prototype=new Parent();
var child=new Child();
child.play; //[1,2,3]
【缺点】原型对象的属性是共享的。
3、组合式继承
function Parent(){
this.name='parent';
this.play=[1,2,3];
}
function Child(){
Parent.call(this);
this.type='child';
}
Child.prototype=Object.create(Parent.prototype);
Child.prototype.constructor=Child;
var child=new Child();
child.name; //parent
网友评论