Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 继承 #3

Open
lixiangwei opened this issue Feb 27, 2017 · 0 comments
Open

JavaScript 继承 #3

lixiangwei opened this issue Feb 27, 2017 · 0 comments

Comments

@lixiangwei
Copy link
Owner

lixiangwei commented Feb 27, 2017

第一种挺常用的(构造函数默认首字母大写,约定俗成):

function Father(name) {
    //定义属性
    this.name = name;
}
//定义方法
Father.prototype.getName = function() {
   alert(this.name);
};
//子类
function Child(name, age) {
    //继承父类属性
    Father.call(this, name);
    this.age = age;
}
//继承父类方法
Child.prototype = new Father();
//定义子类方法
Child.prototype.getAge = function(){
    alert(this.age);
};
//创建实例
var instance1 = new Child(“lxw”, 26);

第二种继承方式:

function inheritPrototype(Child, Father) {
    var prototype = Object.create(Father.prototype);                           
    prototype.constructor = Child;                                                           
    Child.prototype = prototype;                                                        
}

function Father(name) {
    this.name = name;
}
Father.prototype.getName = function() {
    alert(this.name);
};
function Child(name, age) {
    Father.call(this, name);
    this.age = age;
}
inheritPrototype(Child, Father);
Child.prototype.getAge = function() {
    alert(this.age);
};

Object.create实现原理:

Object.create = function(obj) {
    function Temporary(){};
    Temporary.prototype = obj;
    return new Temporary();
}

ES6继承

ES6类的数据类型就是函数,类本身就指向构造函数。typeof Father 返回function

class Father {
    constructor(name) {
        this.name = name;
    }
}
class Child extends Father {
    constructor(name, age) {
        super(name);
         this.age = age;
    }
}
let instance1 = new Child("lxw", 26);

子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。子类只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,是基于对父类实例加工,只有super方法才能返回父类实例。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant