类的创建与继承

一、类的创建

在面向对象编程中,类(class)是对象(object)的模板,定义了同一组对象(又称实例)共有的属性和方法。JavaScript语言里是没有类的概念的,但是我们通过以下方法也可以模拟出类。

1. 利用this关键字:

function User(){
    this.name="Sarah";
    this.age="23";
    this.getInfo=function(){
        return this.name + " " + this.age;
    }
}
//使用类
var user=new User();
alert(user.getInfo());

2. 原型方法

利用prototype关键字和this关键字实现

由于class本质还是一个function,因此它就会拥有一个的prototype属性,当new一个class时,会把class的porototype属性赋值给这个新对象的 __proto__属性。

function User(name){
    this.name=name||"sarah";
    this.age="23";
}
User.prototype={
        getInfo: function(){
            return this.name+" "+this.age;
        }
} 
var  user = new User();
alert(user.getInfo());//访问方法

3. 利用Object.create()方法构造

为了解决"构造函数法"的缺点,更方便地生成对象,Javascript的国际标准ECMAScript第五版(目前通行的是第三版),提出了一个新的方法Object.create()。

User={
        name:'hello',
        age:'23',
        getInfo:function(){
            return this.name + " " + this.age;
        }
}

//使用
var user=Object.create(User);
alert(user.getInfo());

4. ES6引入了Class语法糖

class User{
    constructor(name, age){
        this.name="sarah";
        this.age ="23";
    }
    getInfo(){
        return this.name+' '+this.age;
    }
}

var user = new User();
console.log((user.getInfo()));//Sarah 23
class Person{
    constructor(skin,language){
        this.skin=skin;
        this.language=language;
    }
    say(){
        console.log('I am a Person')
    }
}
console.log(typeof Person);//function
var p = new Person('unkown','unknown'); console.log(p);//Person {skin: "unkown", language: "unknown"} console.log( __proto__==Person.prototype);//ture
 

new一个对象时,会经历以下几个步骤(摘自javascript高级程序设计):
(1)创建一个对象;
(2)将构造函数的作用域赋值给新对象(因此this就指向了这个新对象);
(3)执行构造函数中的代码(为这个新对象添加属性);
(4)返回新对象

constructor 方法是默认的方法,在new一个对象时,自动调用该方法。在一个类中必须有一个constructor,如果没有定义,则会默认添加一个。

二、class的继承

和其他面向对象语言一样,class用extends实现继承。

(1) 子类没有constructor时

class American extends Person{
    aboutMe(){
        console.log(this.skin+' '+this.language)
    }
}

子类American继承父类Person,子类没用定义constrcutor,则默认添加一个,并且在constrcutor中调用super函数,相当于调用父类的构造函数。调用super函数是为了在子类中获得父类的this,调用之后this指向子类。也就是父类.prototype.constructor.call(this)。

(2) 子类有constructor

子类必须在constructor方法中调用super方法,否则new实例时会报错。因为子类没有自己的this对象,而是继承父类的this对象。如果不调用super函数,子类就得不到this对象。super()作为父类的构造函数,只能出现在子类的constructor()中;但是super指向父类的原型对象,可以调用父类的属性和方法。
class Chinese extends Person{
    constructor(skin,language,positon){
        //console.log(this);//报错
        super(skin,language);
        //super();
        //console.log(this);调用super后得到了this,不报错
        this.positon=positon;
    }
    aboutMe(){
        console.log(this.skin+' '+this.language+' '+this.positon);
    }
}

猜你喜欢

转载自www.cnblogs.com/sarah-wen/p/10811857.html