欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Javascript实现继承的方法

程序员文章站 2024-03-18 21:20:22
...

  JavaScript可以有许多种方法来实现继承。

  1.原型继承

  下面的代码使用原型继承来创建一个Pet的对象,和一个继承它的Cat对象。

/**
 * Created by ztt on 2017/7/24.
 */

//Define a Pet object. Pass it a name and number of legs.
var Pet = function (name,legs) {
    this.name = name;
    this.legs = legs;
};

//Create a method that shows the Pet's name and number of legs.
Pet.prototype.getDetails = function () {
    return this.name + ' has ' + this.legs + ' legs ';
};

//Define a Cat object,inheriting from Pet.
var Cat = function (name) {
    Pet.call(this,name,4);//Call the parent object's constructor.
};

//This line performs the inheritance from Pet.
Cat.prototype.action = function () {
    return 'Catch a bird';
};

//Create an instance of Cat in petCat.
var petCat = new Cat('Felix');

var details = petCat.getDetails();  //'Felix has 4 legs'.
var action = petCat.action();       //'Catch a bird'.
petCat.name = 'Sylvester';          //Change petCat's name.
petCat.legs = 7;                    //Change petCat's number of legs!!!
details = petCat.getDetails();      //'Sylvester has 7 legs'.

  上述代码可以工作,但不是特别优雅。如果熟悉其它OOP语言,比如C++或者Java,new声明是好理解的。但是关键字prototype显得很啰嗦,并没有隐私;注意外部代码将petCat的legs属性改成了一个不合理的值:7。这种继承方法没有提供对外部继承的保护,在涉及多个程序员的复杂项目中这个缺点也许会影响很大。


  2.函数继承

  JavaScript有一个选项可以无序使用prototype或new,而是利用JavaScript的“函数继承”特性。

  

/**
 * Created by ztt on 2017/7/24.
 */

//Define a Pet object. Pass it a name and number of legs.
var pet = function (name,legs) {
    //Create an object literal (that). Include a name property for public use
    //and a getDetails() function. Legs will remain private.
    //Any local variables defined here or passed to pet as arguments will remain
    //private, but still be accessible from functions defined below.
    var that = {
        name: name,
        getDetails: function () {
            //Due to JavaScript's scoping rules, the legs variable
            //will be available in here (a closure) despite being
            //inaccessible from outside the pet object.
            return this.name + ' has ' + this.legs + ' legs ';
        }
    };
    return that;
};

//Define a Cat object,inheriting from Pet.
var Cat = function (name) {
    var that = pet(name,4); //Inherit from pet.
    //Augment cat with an action method.
    that.action = function () {
        return 'Catch a bird';
    };
    return that;
};

//Create an instance of Cat in petCat.
var petCat2 = Cat('Felix');

var details = petCat2.getDetails();  //'Felix has 4 legs'.
var action = petCat2.action();       //'Catch a bird'.
petCat2.name = 'Sylvester';          //We can change the name.
petCat2.legs = 7;                    //But not the number of legs!
details = petCat2.getDetails();      //'Sylvester has 4 legs'.

  这里没有prototype,而且所有东西都封装得很漂亮。最重要的是:legs变量是私有的。如果尝试从cat外部修改不存在的公共legs属性,仅导致创建一个没有用过的legs属性。真正的legs值安全地保存在pet的getDetails()方法创建的闭包内部。闭包在函数执行结束后,保持了函数的局部变量。在这个离职中方这个函数指的是pet()。