在 Javascript 中扩展对象 [英] Extending an Object in Javascript

查看:21
本文介绍了在 Javascript 中扩展对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从 Java 转换为 Javascript,我很难弄清楚如何按照我想要的方式扩展对象.>

我在互联网上看到有几个人使用一种称为扩展对象的方法.代码将如下所示:

var Person = {name : '空白',年龄 : 22}var Robot = Person.extend({name : '机器人',年龄 : 4)}var 机器人 = 新机器人();警报(机器人名称);//应该返回'Robo'

有人知道怎么做吗?我听说你需要写

Object.prototype.extend = function(...);

但我不知道如何让这个系统工作.如果不可能,请告诉我另一个扩展对象的替代方法.

解决方案

您想从 Person 的原型对象继承":

var Person = function (name) {this.name = 名称;this.type = '人类';};Person.prototype.info = function () {console.log("Name:", this.name, "Type:", this.type);};var Robot = 函数(名称){Person.apply(this, arguments);this.type = '机器人';};Robot.prototype = Person.prototype;//将原型设置为 Person 的Robot.prototype.constructor = 机器人;//将构造函数设置回机器人person = new Person("Bob");机器人 = 新机器人(布特罗斯");人信息();//姓名:Bob 类型:人类机器人信息();//名称:Boutros 类型:机器人

I am currently transforming from Java to Javascript, and it's a bit hard for me to figure out how to extend objects the way I want it to do.

I've seen several people on the internet use a method called extend on object. The code will look like this:

var Person = {
   name : 'Blank',
   age  : 22
}

var Robot = Person.extend({
   name : 'Robo',
   age  : 4
)}

var robot = new Robot();
alert(robot.name); //Should return 'Robo'

Does anyone know how to make this work? I've heard that you need to write

Object.prototype.extend = function(...);

But I don't know how to make this system work. If it is not possible, please show me another alternative that extends an object.

解决方案

You want to 'inherit' from Person's prototype object:

var Person = function (name) {
    this.name = name;
    this.type = 'human';
};

Person.prototype.info = function () {
    console.log("Name:", this.name, "Type:", this.type);
};

var Robot = function (name) {
    Person.apply(this, arguments);
    this.type = 'robot';
};

Robot.prototype = Person.prototype;  // Set prototype to Person's
Robot.prototype.constructor = Robot; // Set constructor back to Robot

person = new Person("Bob");
robot = new Robot("Boutros");

person.info();
// Name: Bob Type: human

robot.info();
// Name: Boutros Type: robot

这篇关于在 Javascript 中扩展对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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