javascript的继承

其他语言(如)Java是类的继承,而javascript是对象直接继承对象。javascript继承有几种常见的模式。

伪类

javascript函数构造器的概念使其看上去更像Java这种基于类的语言,实际上这是有迷惑性的。

创建函数时,新函数对象会被自动添加一个prototype属性,prototype的值是一个对象,这个对象包含一个constructor属性,值为新函数对象。

this.prototype = {"constructor" : this};

但使用new调用函数时,函数的执行方式会被修改:

  1. 创建一个新对象,继承自构造器函数的prototype对象
  2. 调用构造器函数,类似于使用apply()的方式,绑定新对象的“this”,并传入构造器的参数
  3. 返回新对象
function Person(race)
{
    this.race = race;
}
function Student(name)
{
    this.name = name;
}
Student.prototype = new Person("yellow");
Student.prototype.say_hello = function()
{
    console.log(this.race + " " + this.name);
};

var tom = new Student("tom");
tom.say_hello();

这种方式实际上看起来很怪异,难以理解,不推荐使用。

原型

在纯粹的原型模式中,理解和使用继承更加简单。使用对象章节的create函数把丑陋的细节隐藏起来。

if(typeof Object.create != "function")
{
    Object.create = function(o)
    {
        var F = function() {};
        F.prototype = o;
        return new F;
    }
}

实现继承时,不再考虑伪类,而是只考虑对象。

var student = {
    "grade" : 3
};
var tom = Object.create(student);
tom.name = "tom";

函数化模式

函数化模式可以实现私有属性,如下例子中,school属性是完全私有的,只能通过get_school函数访问。

function Student(spec)
{
    var that = {};
    that.name = spec.name;
    that.age = spec.age;
    that.get_school = function()
    {
        return spec.school;
    };
    return that;
}
var tom = Student({"name" : "tom", "age" : 10, "school" : "MIT"});
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。