【问题标题】:Write a function "extends" which simplifies the JS based inheritance [duplicate]编写一个“扩展”函数来简化基于 JS 的继承 [重复]
【发布时间】:2015-07-07 04:06:40
【问题描述】:

我是 Java 脚本世界的新手,我们怎么能用 Java 脚本编写代码。

 function Car() {
     this.type = "Car";
   };

function Ferrari() {
     this.name = "Ferrari";
   };

Ferrari.extends(Car);
   var f = new Ferrari();
   f.name // Ferrari
   f.type // Car

当我关注eloquentjavascript book 时,没有一个答案可以帮助我

【问题讨论】:

  • 查看这个答案:stackoverflow.com/a/10430875/921204 - 还要确保阅读 cmets。
  • 虽然副本与问题不完全匹配,但接受的答案涵盖了它(以及许多其他内容)。互联网上还有许多其他资源可用于扩展 javascript“类”。一旦你对这些进行了一些研究并提出了一个首选的解决方案,也可以随时提出相关问题。 :-)

标签: javascript


【解决方案1】:

Javascipt 是一种采用prototypical 方法的混合语言。在 js 上下文中“扩展”就是通过原型继承。一些现代浏览器支持 Object.create() ,它在内部迭代每个原型属性并复制。

这个sn-p来自MDN

Examples
Example: Classical inheritance with Object.create()

Below is an example of how to use Object.create() to achieve classical inheritance. This is for single inheritance, which is all that JavaScript supports.

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle? ' + (rect instanceof Rectangle)); // true
console.log('Is rect an instance of Shape? ' + (rect instanceof Shape)); // true
rect.move(1, 1); // Outputs, 'Shape moved.'

希望这会有所帮助。

【讨论】:

  • 那么我们如何编写自己的扩展方法
  • 是的,但是通过对象的原型。上面的示例“子类扩展了超类”。但请查看版主提供的类似主题的链接以及答案。祝你好运,玩得开心!
猜你喜欢
  • 2015-11-05
  • 1970-01-01
  • 2013-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-01
  • 2014-11-06
  • 1970-01-01
相关资源
最近更新 更多