Object create()与 new

Object.create() 方法会使用指定的原型对象及其属性去创建一个新的对象。

返回值:在指定原型对象上添加新属性后的对象。”-------摘自MDN

通俗一点就是一个新的对象,可以继承一个对象的属性,并且可以添加新属性,小栗子:

var a = {
   name : '小七哥'
}
var b = Object.create(
    a,
    {
       age : { value : 18}    //一定要写value,不然undifined
    }
)
console.log(b):



实现类式继承:

// Shape - 父类(superclass)
function Shape() {
  this.x = 0;
  this.y = 0;
}

// 父类的方法
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - 子类(subclass)
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// 子类续承父类
Rectangle.prototype = Object.create(Shape.prototype);// 这边会改变,Rectangle.prototype.constructor ,变成了Shape()

Rectangle.prototype.constructor = Rectangle;//重新指定回来为Rectangle()
var rect = new Rectangle();
console.log(rect instanceof Rectangle); // true
console.log(rect instanceof Shape); // true

以上通过Rectangle.prototype = Object.create(Shape.prototype)实现继承,这时候打印

Rectangle.prototype 会发现继承了Shape的原型,

那么通过Rectangle.prototype = new Shape()也可以实现继承,那么区别呢,打印Rectangle.prototype就可以看到,它是整个Shape的实例,除了继承的Shape原型外,还有Shape的实例。

下面例子也是:

        function Parent(){
		this.name = '大人类';
		this.age = 30;
	}
	Parent.prototype.getParentName=function(){
		console.log(this.name);
	}
	function Child1(){
		this.name='小人1类';
	}
	Child1.prototype=new Parent();
	console.log(Child1);
	console.log(Child1.prototype);

	function Child2(){
		this.name='小人2类'
	}
	Child2.prototype = Object.create(Parent.prototype);
	console.log(Child2);
	console.log(Child2.prototype);


new 继承过来的,在原型链上除了继承Parent原型之外还继承了其实例。这种情况下,child2实例将会无法访问到Parent中的age:

var person1 = new Child1();
var person2 = new Child2();
console.log(person1.name);// 小人1类
console.log(person1.age);//30
console.log(person2.age);//undefined
并且,通过读取person1.name我们可以看到,访问一个属性,当实例继承的构造函数中有该属性时,直接读取继承而来的属性,如果没有该属性,则去原型链上查找,如果找到则返回原型链上继承的该属性,如果找不到则返回undefined.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值