非常简单的Javascript继承 [英] Very simple Javascript inheritance

查看:83
本文介绍了非常简单的Javascript继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JavaScript中使用超级简单继承的超级可读版本。这是一些自动生成的代码,我无法使用外部函数或库。

I need a super-readable version of this super simple inheritance in JavaScript. This is some auto-generated code, where I can't afford to be using external functions or libraries.

我真正想要的是,假设Point3d从Point继承 ,我想要这样的东西:

What I really want is, assuming Point3d "inherits" from Point, I want something like this:

function Point(x,y) {
  this.x = x;
  this.y = y;
}

function Point3d(x,y,z) {
  Point(x, y);
  this.z = z;
}

除非它实际上不起作用:

Except it doesn't actually work:

var pt = new Point3d(230,30,11);
// but x and y are in global scope, they should be in pt.x and pt.y :(

一个可能的选择,在代码生成中会复制所有成员 - 但由于Javascript是基于原型的,我想这很容易做到(如果我真的知道Javascript)

One possible option, would in the code generation duplicate all the members -- but since Javascript is prototype based, I would imagine this is easy to do properly (if I actually knew Javascript)

谢谢

推荐答案

应用 Point 使用 .call() Point3d 对象的构造函数。

Apply the Point constructor to the Point3d object using .call().

function Point3d(x,y,z) {
  Point.call(this, x, y);
  this.z = z;
}

http ://jsfiddle.net/MSfu5/

.call 方法设置<的值您正在调用的函数中code>此。

此处我们将其设置为新的点3d 正在构造的对象。

Here we're setting it to the new Point 3d object being constructed.

如果点原型 Point3d 应该继承,你可以使 Point3d.prototype 对象成为的空实例点

If there's anything on the Point prototype that Point3d should inherit, you can make the Point3d.prototype object an empty instance of Point.

这篇关于非常简单的Javascript继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆