关于js面向对象的认识

一、创建一个类

//定义构造器
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的实例b
var b=new item({'itemname':'b'});
//b的constructor指向item
console.log(b.constructor===item); //true 
//b的_proto_属性指向item的的原型链
console.log(Object.getPrototypeOf(b)===item.prototype); //true

b.showName(); //name:b
b.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);

你可能感兴趣的:(关于js面向对象的认识)