javascript – JS中的原型继承以及如何获取父属性

我正在尝试从父级继承属性,但我不清楚正确的方法.

让我们说:

var Animal = function(name){
  this.offspring = [];
  this.name = name;
  return this;
}

Animal.prototype.createOffspring = function(name){
  name = name || 'Baby '+(this.offspring.length+1);
  this.offspring.push(name);
  return this;
}

现在我想添加一个子原型继承,所以我不必手动添加父项中的所有内容.例如,假设我想添加一个基于Animal的Cat

我想这样做,就好像它是动物一样

var pet = new Cat('Kitty');
pet.createOffspring();

无需手动将名称和createOffspring添加到Cat构造函数中,而Cat构造函数实际上只是一个Animal,但具有一些其他附加功能(如.meow()或其他东西).

最佳答案
// Parent
function Animal() {
  this.name = 'An animal';
}

// Some child
function Cat() {
  this.speaks = 'Meow'; 
}
// Here comes inheritence
Cat.prototype = new Animal();
// Or like that
// but don't forget to put all inheritable fields to Animal's prototype
Cat.prototype = Object.create(Animal.prototype); 

// Let 'instanceof' work. Don't forget the following line,// because we eraese the info about constructor of Cat instances.
Cat.prototype.constructor = Cat;
// Add some custom method
Cat.prototype.meow = function() { return this.speaks; }

var cat = new Cat();
var animal = new Animal();

/// Some tests
cat.name; // A animal
animal.name; // An animal
cat.meow(); // Meow!
cat instanceof Cat; // true
cat instanceof Animal; // true

而已?
(UPD:修复原型时出错)
(UPD2:对不起.这是深夜,我犯了很多错误……我一定要睡觉了)

还有另一种解决方案,但其Chrome,特定于FF(可能还有其他):

// Animal and Cat functions from above,but
Cat.prototype = {
  __proto__: Animal.prototype,constructor: Cat,meow: function() { ... }
}

看起来更短,但不会受此诱惑:最好遵循ECMAScript标准.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...