JavaScript 扩展类

2024-02-27

我有一个基类:

function Monster() {
  this.health = 100;
}

Monster.prototype.growl = function() {
  console.log("Grr!");
}

我想扩展并创建另一个类:

function Monkey extends Monster() {
  this.bananaCount = 5;
}

Monkey.prototype.eatBanana {
  this.bananaCount--;
  this.health++; //Accessing variable from parent class monster
  this.growl();  //Accessing function from parent class monster
}

我做了相当多的研究,似乎有许多复杂的解决方案可以用 JavaScript 来实现这一点。在 JS 中实现这一点最简单、最可靠的方法是什么?


以下针对 ES6 进行了更新

2013 年 3 月和 ES5

这个 MDN 文档很好地描述了扩展类:

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

特别是,现在他们处理它:

// define the Person Class
function Person() {}

Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
}

// inherit Person
Student.prototype = Object.create(Person.prototype);

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

// replace the sayHello method
Student.prototype.sayHello = function(){
  alert('hi, I am a student');
}

// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
  alert('goodBye');
}

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true

注意Object.create() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create一些较旧的浏览器不支持,包括 IE8:

如果您需要支持这些,链接的 MDN 文档建议使用 polyfill,或以下近似值:

function createObject(proto) {
    function ctor() { }
    ctor.prototype = proto;
    return new ctor();
}

使用这个就像Student.prototype = createObject(Person.prototype)优于使用new Person()在那它避免调用父级的构造函数 https://stackoverflow.com/a/17952160/568458继承原型时,仅在调用继承者的构造函数时调用父构造函数。

2017 年 5 月和 ES6

值得庆幸的是,JavaScript 设计者听到了我们的帮助请求,并采取了更合适的方法来解决这个问题。

MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Sub_classing_with_extends关于 ES6 类继承还有另一个很好的例子,但我将展示与上面在 ES6 中重现的完全相同的一组类:

class Person {
    sayHello() {
        alert('hello');
    }

    walk() {
        alert('I am walking!');
    }
}

class Student extends Person {
    sayGoodBye() {
        alert('goodBye');
    }

    sayHello() {
        alert('hi, I am a student');
    }
}

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true

干净且易于理解,就像我们都想要的那样。请记住,虽然 ES6 很常见,但它并非所有地方都支持 https://caniuse.com/#feat=es6-class:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

JavaScript 扩展类 的相关文章