javascript面向对象继承

javascript面向对象继承

by Abruzzi Hraig

HTML

<div class="content">
    
</div>

JavaScript

// 1.Pseudoclassical继承模式 构造函数申明类,通过new创建实例对象
function Animal(){
    this.run = function(){
        alert(this.name + '奔跑');
    };
}
function Dog(){
    this.name = '狗';
}
Dog.prototype = new Animal();

var s = new Dog();
$('.content').append(s.name);
s.run();

// 2.原型继承Object.create创建对象,直接声明对象,通过Object.create()继承对象实例
// 此时Object.create(proto, x)
var animal = {
    run: function(){
        alert(this.name + '奔跑');
    }
}

var cat = Object.create(animal);
cat.name = '猫';
cat.run();