首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何让构造函数继承Javascript中的构造函数?

如何让构造函数继承Javascript中的构造函数?
EN

Stack Overflow用户
提问于 2010-02-15 07:47:14
回答 2查看 1K关注 0票数 8

因此,我正在学习Javascript和它所有的原型的好处,我被以下几点难住了:

假设我有这个

代码语言:javascript
运行
复制
var Animal = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   this.a = a;
   this.b = b;
   //...etc...
};

var x = new Animal(1,2,3....);

现在我如何创建一个从Animal构造函数继承的Cat构造函数,这样我就不必再输入超长的参数了?

换句话说,我不想这样做:

代码语言:javascript
运行
复制
var Cat = function (a, b, c, d, e, f, g, h, i, j, k , l, m, n){
   this.a = a;
   this.b = b;
   //...etc...
};

// inherit functions if any
Cat.prototype = new Animal;

var y = new Cat(1,2,3....);

提前感谢!J

EN

Stack Overflow用户

发布于 2010-02-15 11:07:57

记住像这样的长参数列表的顺序和含义很快就会变得单调乏味。

如果您将新Animal的属性作为对象传递,则可以添加一些灵活性-而且它并不像一长串参数索引那样难以记忆。

代码语言:javascript
运行
复制
function Animal(features){
 for(var p in features){
  this[p]= features[p];
 }
};

You can give every cat some basic cat features automatically, 
and add specifics when you make a new cat.

function Cat(features){
 for(var p in features){
  this[p]= features[p];
 }
}
Cat.prototype= new Animal({legs: 4, eats: 'meat', type: 'mammal', whiskers: true});
Cat.prototype.constructor=Cat;

var Tiger= new Cat({tail: true, hunter: true});
Tiger begins with these properties:

tail: true
hunter: true
legs: 4
eats: meat
type: mammal
whiskers: true
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2263353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档