谈谈js原型和原型链

2017-04-11  本文已影响0人  zhangjianli

谈到原型和原型链,相信很多人都会想到js类与继承,但由于js是基于对象的语言,并不是面向对象的,所以它本身并没有类的概念,当然,也没有继承的概念,但是我们通常通过对象和原型的方式来实现类似类继承机制

function Parent(){}

parent可表示一个类,想要实例化它,直接

var p1=new Parent();

就可以

class Parent(name){
    this.name=name;
    ths.hobby=['sing','dance','shopping'];
}
Parent.prototype.sayHello=function(){
    console.log('hello');
}//属性写在构造函数中,方法写在prototype下
class Child(){
Parent.call(this);//用于继承属性,解决属性为引用类型时一个改变全改变问题
}
Child.prototype= new Parent();//用于继承,继承其所有
Child.prototype.constructor = Child;**//将因为上一步将.costructor修改的属性改为正确值
上一篇 下一篇

猜你喜欢

热点阅读