关于js面向对象的认识

来源:互联网 发布:淘宝店铺买家监控软件 编辑:程序博客网 时间:2024/05/16 01:36

一、创建一个类

//定义构造器function item(o){    this.itemname=o.itemname;    this.price=o.price;    this.count=o.count;}//在原型链上定义需要继承的函数item.prototype={    showName:function(){        console.log("name:"+this.itemname);    }}//以下方式,直接写在item上无法实现继承item.show=function(){    console.log(123);}

二、实例化

//创建item的实例bvar b=new item({'itemname':'b'});//b的constructor指向itemconsole.log(b.constructor===item); //true //b的_proto_属性指向item的的原型链console.log(Object.getPrototypeOf(b)===item.prototype); //trueb.showName(); //name:bb.show(); //报错,只能继承原型链上的函数

三、创建item的子类,item2

function item2(o){    item.call(this,o);//使用call方法调用父类构造函数    this.price=9.98;//覆盖父类price};item2.prototype= item.prototype;//继承父类的原型链item2.prototype.constructor=item2;//改变constructor的指向var b2= new item2({'itemname':'b2'}) b2.showName();

四、ES6中的继承

//定义类class People{    constructor(o){        this.name=o.name;        this.age=o.age;        this.state=o.state;    }    showPeople(){        console.log("姓名:"+this.name+";年龄:"+this.age+";身份:"+this.state);    }}var p1=new People({'name':'p1','age':'42','state':'中年'});p1.showPeople();//子类Student继承自父类class Student extends People{    constructor(o){        super(o);//继承父类的构造方法        this.state='学生'; //重写父类的某个属性        this.school=o.school;//x新增子类的属性    }    showStudent(){        console.log("姓名:"+this.name+";年龄:"+this.age+";身份:"+this.state+";学校:"+this.school);    }}var s1=new Student({'name':'p1','age':'42','state':'中年','school':'杭电大学'});console.log(s1);
0 0
原创粉丝点击