`
holdbelief
  • 浏览: 697047 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JavaScript 从类继承

阅读更多

从类继承

到这里,我们已经了解了构造函数和原型对象如何使您在JavaScript中模拟类。您可以看到,原型链可以确保所有对象都有Object.prototype的公用方法,以及如何使用闭包来模拟类的私有成员。但这里还缺少点什么。您尚未看到如何从类派生,这在C#中是每天必做的工作。遗憾的是,在JavaScript中从类继承并非像在C#中键入冒号即可继承那样简单,它需要进行更多操作。另一方面,JavaScript非常灵活,可以有很多从类继承的方式。

例如,有一个积累Pet,它有一个派生类Dog,如图9所示。这个在JavaScript中如何实现呢?Pet类很容易。您已经看见如何实现它了:


// class Pet
function Pet(name)
{
        this.getName = function()
        {
               return name;
        }
        this.setName = function(newName)
        {
               name = newName;
        }
}

Pet.prototype.toString = function()
{
        return "This pet's name is: " + this.getName();
}
// end of class Pet

var parrotty = new Pet("Parrotty the Parrot");
alert(parrotty);

 现在,如何创建从Pet派生的类Dog呢?在图9种可以看到,Dog有另一个属性breed,它改写了Pet的toString方法(注意,JavaScript的约定是方法和属性的名称使用camel大小写,而不是在C#中建议的Pascal大小写)。图10显示如何这样做。

 

Figure 10 从 Pet 类派生

// class Dog : Pet
// public Dog(String name, String breed)
function Dog(name, breed)
{
        // think Dog: base(name)
        Pet.call(this, name);
        this.getBreed = function()
        {
                return breed;
        }
        
        // Breed doesn't change, obviously! It's read only.
        // this.setBreed = function(newBreed){breed = newBreed;}
}

// this makes Dog.prototype inherits from Pet.prototype
Dog.prototype = new Pet();

// remember that Pet.prototype.constructor
// point to Pet. We want out Dog instances' constructor
// to point to Dog.
Dog.prototype.constructor = Dog;

// Now we override Pet.prototype.toString
Dog.prototype.toString = function()
{
        return "This dog's name is: " + this.getName() + " , and its breed " +
        "is: " + this.getBreed();
};
//end of class Dog

var dog = new Dog("Buddy", "Greed Dane");
// test the new toStirng()
alert(dog);

// Testing instanceof (similar to the is operator)
// (dog is Dog)? yes
alert(dog instanceof Dog);
// (dog is Pet)? yes
alert(dog instanceof Pet);
// (dog is Object)? yes
alert(dog instanceof Object);

 所使用的原型 — 替换技巧正确设置了原型链,因此假如使用C#,测试的实例将按预期运行。而且特权方法仍然会按预期运行。

下一节:模拟命名空间

  • 大小: 21.1 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics