Javascript的繼承

繼承1

宣告+定義

function Animal(name) {
    this.name = name;
    this.age = 18;
    this.sayName = function() {
        console.log(this.name + ' and ' + this.age);
    };
};

function Human() {
};

//繼承: Human is a Animal
Human.prototype = new Animal('bad student');

呼叫執行

var student = new Human('good student');
student.sayName();

顯示

bad student and 18

繼承2

宣告+定義

function Animal(name) {
    this.name = name;
    this.age = 18;
    this.sayName = function() {
        console.log(this.name + ' and ' + this.age);
    };
};

function Human() {
};

//繼承: Human is a Animal
Human.prototype = new Animal();

呼叫執行

var student = new Human('good student');
student.sayName();

顯示

undefined student and 18

繼承3

宣告+定義

function Animal(name) {
    this.name = name;
    this.age = 18;
    this.sayName = function() {
        console.log(this.name + ' and ' + this.age);
    };
};

function Human(name) {
    this.name = name
};

//繼承: Human is a Animal
Human.prototype = new Animal('bad student');

呼叫執行

var student = new Human('good student');
student.sayName();

顯示

good student and 18

沒有留言:

張貼留言

(什麼是留言欄訊息?)