我读到,在原型(prototype)中声明对象方法是一种很好的方法,因为它可以节省内存并允许随时更改所有对象的实现。 但是,当我需要为使用原型(prototype)方法声明的对象设置基对象时,我需要做什么? 示例:
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 中的原型(prototype)属性是作为方法的自定义对象实现的)?
最佳答案
ES5 版本(仍然最常见,但我不推荐它 - 请参阅 ES6 版本)
基于这篇文章here你需要像这样使用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。
关于Javascript在原型(prototype)中声明方法时设置基础对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44873190/