我读到在原型中声明对象方法是一种很好的方法,因为它可以节省内存并允许随时更改所有对象的实现。但是当我需要为使用原型方法声明的对象设置基对象时,我需要做什么?例子:
function Animal() {
this.age = 0;
this.weight = 0;
//other properties
}
Animal.prototype = {
//some methods for Animal
}
function Dog() {
//properties for Dog
}
Dog.prototype = {
//some methods for Dog
}
那么,如何将 Animal 设置为 Dog 的基类(对象)(因为 Dog 中的原型属性是作为方法的自定义对象实现的)?
ES5 版本(仍然是最常见的,但我不推荐它 - 请参阅 ES6 版本)
根据这里的这篇文章,您需要像这样使用 Object.create:
function Animal() {}
Animal.prototype = {};
function Dog() {}
Dog.prototype = Object.create( Animal.prototype );
另请参阅Object.assign 的此解决方案(遗憾的是 IE 不支持它)
ES6版本
class Animal {
// all your methods come in here. No more prototype needed.
}
class Dog extends Animal {
}
尽管大多数浏览器还不完全支持 ES6,但您已经可以使用它了。使用babel来转译你的 JS。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句