在Javascript中扩展对象 [英] Extending an Object in Javascript
问题描述
我现在正在从Java转换为Javascript,并且我很难弄清楚如何按照我希望的方式扩展对象。
我已经看到互联网上的几个人使用了一种称为扩展对象的方法。代码如下所示:
var Person = {
name:'Blank',
age :22
}
var Robot = Person.extend({
name:'Robo',
age:4
)}
var robot = new Robot();
alert(robot.name); //应该返回'Robo'
有人知道如何使这项工作成功吗?
我听说你需要编写
Object.prototype.extend = function(...);
但我不知道如何让这个系统工作。如果这是不可能的,请向我展示另一个扩展对象的替代方案。
在使用代码之前,请检查user2491400中有关简单分配给
原型
的副作用的评论。 原始答案:
您想从Person的原型对象'继承':
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.name = name;
this.type ='robot';
}
Robot.prototype = Person.prototype; //将原型设置为Person的
Robot.prototype.constructor = Robot; //将构造函数设置回Robot
$ b person = new Person(Bob);
robot = new Robot(Boutros);
person.info();
//名称:Bob类型:人类
robot.info();
//名称: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.
Edit:
Before using the code, please check the comments from user2491400 that reports about the side effects of simply assigning to prototype
.
Original answer:
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.name = name;
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屋!