Javascript在原型中声明方法时设置基对象
我读到在prototype中声明对象方法是一种很好的方法,因为它可以节省内存并允许在任何时候更改所有对象的实现。 但当我需要为使用原型方法声明的对象设置基对象时,我需要做什么呢? 例如:Javascript在原型中声明方法时设置基对象,javascript,inheritance,prototype,Javascript,Inheritance,Prototype,我读到在prototype中声明对象方法是一种很好的方法,因为它可以节省内存并允许在任何时候更改所有对象的实现。 但当我需要为使用原型方法声明的对象设置基对象时,我需要做什么呢? 例如: 那么,如何将Animal设置为Dog的基类(对象)(因为Dog中的prototype属性是作为方法的自定义对象实现的)?ES5版本(仍然是最常见的,但我不推荐它-请参阅ES6版本) 基于此帖子,您需要使用Object.create,如下所示: function Animal() {} Animal.protot
那么,如何将Animal设置为Dog的基类(对象)(因为Dog中的prototype属性是作为方法的自定义对象实现的)?ES5版本(仍然是最常见的,但我不推荐它-请参阅ES6版本) 基于此帖子,您需要使用Object.create,如下所示:
function Animal() {}
Animal.prototype = {};
function Dog() {}
Dog.prototype = Object.create( Animal.prototype );
还可以通过查看此解决方案(遗憾的是IE不支持此解决方案)
ES6版本
class Animal {
// all your methods come in here. No more prototype needed.
}
class Dog extends Animal {
}
即使大多数浏览器还不完全支持ES6,您也可以使用它。用于传输您的JS。ES5版本(仍然是最常见的,但我不推荐它-请参阅ES6版本) 基于此帖子,您需要使用Object.create,如下所示:
function Animal() {}
Animal.prototype = {};
function Dog() {}
Dog.prototype = Object.create( Animal.prototype );
还可以通过查看此解决方案(遗憾的是IE不支持此解决方案)
ES6版本
class Animal {
// all your methods come in here. No more prototype needed.
}
class Dog extends Animal {
}
即使大多数浏览器还不完全支持ES6,您也可以使用它。用于传输JS。您可以将
动物
定义为函数,并使用其构造函数在狗
原型中设置其实例:
Dog.prototype = new Animal();
更完整的代码:
var Animal = function () {
this.age = 0;
this.weight = 0;
this.age = function () {
return this.age;
}
// define other methods ...
// ...
return this;
};
var Dog = function () {
// overriding the age
this.age= 10;
// define or override methods ...
// ...
return this;
};
// Dog extends animal
Dog.prototype = new Animal();
// Creating an instance of Dog.
var dog = new Dog();
您可以将
Animal
定义为函数,并使用其构造函数在Dog
原型中设置其实例:
Dog.prototype = new Animal();
更完整的代码:
var Animal = function () {
this.age = 0;
this.weight = 0;
this.age = function () {
return this.age;
}
// define other methods ...
// ...
return this;
};
var Dog = function () {
// overriding the age
this.age= 10;
// define or override methods ...
// ...
return this;
};
// Dog extends animal
Dog.prototype = new Animal();
// Creating an instance of Dog.
var dog = new Dog();
哦,太简单了,谢谢。但当我将Dog.prototype设置为Animal.prototype时,我可以访问方法,但不能访问Animal的属性。或者我不应该访问它们?我应该调用getter和setter,对吗?嗯,我会使用extend变量。这仍然是普遍的做法。当然,这取决于你在做什么哦,很简单,谢谢。但当我将Dog.prototype设置为Animal.prototype时,我可以访问方法,但不能访问Animal的属性。或者我不应该访问它们?我应该调用getter和setter,对吗?嗯,我会使用extend变量。这仍然是普遍的做法。当然,这取决于你在做什么