在Javascript中扩展对象
我目前正在从Java转换到Javascript,要想弄清楚如何按我所希望的方式扩展对象有点困难 我见过一些人在互联网上使用一种叫做扩展对象的方法。代码如下所示:在Javascript中扩展对象,javascript,function,object,prototype,extends,Javascript,Function,Object,Prototype,Extends,我目前正在从Java转换到Javascript,要想弄清楚如何按我所希望的方式扩展对象有点困难 我见过一些人在互联网上使用一种叫做扩展对象的方法。代码如下所示: var Person = { name : 'Blank', age : 22 } var Robot = Person.extend({ name : 'Robo', age : 4 )} var robot = new Robot(); alert(robot.name); //Should retu
var Person = {
name : 'Blank',
age : 22
}
var Robot = Person.extend({
name : 'Robo',
age : 4
)}
var robot = new Robot();
alert(robot.name); //Should return 'Robo'
有人知道怎么做吗?
我听说你需要写信
Object.prototype.extend = function(...);
但我不知道如何让这个系统工作。如果不可能,请向我展示另一种扩展对象的替代方法。您希望从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.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
function Person(name){
this.name = name;
this.type = 'human';
}
Person.prototype.info = function(){
console.log("Name:", this.name, "Type:", this.type);
}
function Robot(name){
Person.call(this, name)
this.type = 'robot';
}
// Set Robot's prototype to Person's prototype by
// creating a new object that inherits from Person.prototype,
// and assigning it to Robot.prototype
Robot.prototype = Object.create(Person.prototype);
// Set constructor back to Robot
Robot.prototype.constructor = Robot;
你可能想考虑使用类似的帮助库,它有.
这也是一种通过查看源代码来学习的好方法。非常有用。如果您还没有找到方法,请使用JavaScript对象的关联属性向
对象.prototype添加扩展函数,如下所示
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
var o = { member: "some member" };
var x = { extension: "some extension" };
o.extend(x);
然后,您可以使用此功能,如下所示
Object.prototype.extend = function(obj) {
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
this[i] = obj[i];
}
}
};
var o = { member: "some member" };
var x = { extension: "some extension" };
o.extend(x);
又过了一年,我可以告诉你还有一个很好的答案
如果您不喜欢为扩展对象/类而进行原型设计的工作方式,请考虑以下几点:
可能性的快速示例代码(以及更多):
不同的方法:
根据@osahyun的回答,我发现以下是从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.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
function Person(name){
this.name = name;
this.type = 'human';
}
Person.prototype.info = function(){
console.log("Name:", this.name, "Type:", this.type);
}
function Robot(name){
Person.call(this, name)
this.type = 'robot';
}
// Set Robot's prototype to Person's prototype by
// creating a new object that inherits from Person.prototype,
// and assigning it to Robot.prototype
Robot.prototype = Object.create(Person.prototype);
// Set constructor back to Robot
Robot.prototype.constructor = Robot;
创建新实例:
var person = new Person("Bob");
var robot = new Robot("Boutros");
person.info(); // Name: Bob Type: human
robot.info(); // Name: Boutros Type: robot
现在,通过使用:
同时检查文档。World,不带“new”关键字。
以及使用Object.create()的更简单的“散文式”语法。
*此示例针对ES6类和TypeScript进行了更新
首先,事实上,Javascript是一种,而不是基于类的。它的真实本质在下面的原型形式中得到了表达,你可能会看到它非常简单,散文般,但却很强大
太长,读不下去了
constperson={
姓名:'匿名',//此人有姓名
greet:function(){console.log(`Hi,我是${this.name}.`}
}
const jack=Object.create(Person)//杰克是一个人
jack.name='jack'//并且有一个名字'jack'
Helen()//输出“嗨,我是杰克。”
这免除了有时复杂的构造函数模式。新对象继承了旧对象,但能够拥有自己的属性。如果我们试图从新对象(#greet()
)中获取成员,而新对象jack
缺少该成员,则旧对象Person
将提供该成员
在
您不需要构造函数,不需要新的实例化(),不需要超级构造函数,不需要自制的构造函数。您只需创建对象,然后对其进行扩展或变形
这种模式还提供了,和
打字稿
TypeScript等效项看起来相同:
interface Person {
name: string,
greet: Function
}
const Person = {
name: 'Anonymous',
greet: function(): void { console.log(`Hi, I am ${this.name}.` }
}
const jack: Person = Object.create(Person)
jack.name = 'Jack'
jack.greet()
散文式语法:Person
prototype
const Person={
//属性
名字:'匿名',
姓氏:“匿名”,
出生年份:0,
类型:'人类',
//方法
name(){返回this.firstName+''+this.lastName},
问候{
console.log('嗨,我的名字是'+this.name()+',我是'+this.type+'))
},
年龄(){
//年龄是出生时间的函数。
}
}
const person=Object.create(person)//就是这样!
清晰明了。它的简单不影响功能。请继续阅读
创建个人的后代/副本
注意:正确的术语是原型
,以及它们的后代/副本
。没有类
,也不需要实例
const Skywalker=Object.create(Person)
天行者.lastName='Skywalker'
const anakin=Object.create(天行者)
anakin.firstName='anakin'
阿纳金。生日='442 BBY'
anakin.gender='male'//您可以附加新属性。
阿纳金。哈雷()/“嗨,我叫阿纳金·天行者,我是人类。”
Person.isPrototypeOf(天行者)//输出true
Person.isPrototypeOf(anakin)//输出true
isPrototypeOf(anakin)//输出true
如果你觉得放弃构造函数而不是直接分配不太安全,那就公平。一种常见的方法是附加一个#create
方法:
Skywalker.create=function(名字、性别、出生年份){
让天行者=Object.create(天行者)
对象。分配(天行者{
名字,
生日,
性别,,
姓:“天行者”,
类型:“人类”
})
返回天行者
}
const anakin=Skywalker.create('anakin','male','442 BBY')
将人
原型分支到机器人
当您将机器人
后代从人
原型分支时,您不会影响天行者
和阿纳金
:
//通过扩展“Person”原型创建“Robot”原型:
const Robot=Object.create(Person)
Robot.type='Robot'
附加机器人独有的方法
Robot.machineGreet=function(){
/*将字符串转换为二进制*/
}
//变异“Robot”对象不会影响“Person”原型及其后代
anakin.machineGreet()//错误
Person.isPrototypeOf(Robot)//输出true
Robot.isPrototypeOf(天行者)//输出为false
在TypeScript中,您还需要扩展Person
界面:
interface Robot extends Person {
machineGreet: Function
}
const Robot: Robot = Object.create(Person)
Robot.machineGreet = function(): void { console.log(101010) }
你可以有混合器,因为…达斯·维德是人类还是机器人?
const-darthVader=Object.create(anakin)
//为简洁起见,将跳过属性指定,因为您现在已了解要点。
分配对象(darthVader、Robot)
达斯·维德获得了机器人的方法:
interface Robot extends Person {
machineGreet: Function
}
const Robot: Robot = Object.create(Person)
Robot.machineGreet = function(): void { console.log(101010) }
darthVader.greet()//继承自'Person',输出“嗨,我叫达斯·维德…”
darthVader.machineGreet()//从“Robot”继承,输出001010011010。。。
以及其他奇怪的事情:
interface Robot extends Person {
machineGreet: Function
}
const Robot: Robot = Object.create(Person)
Robot.machineGreet = function(): void { console.log(101010) }
console.log(darthVader.type)//输出
class Square extends Polygon {
constructor(length) {
// Here, it calls the parent class' constructor with lengths
// provided for the Polygon's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value; }
}
var mergedObj = { ...Obj1, ...Obj2 };
var mergedObj = Object.assign({}, Obj1, Obj2);
Object.prototype.extend = function(object) {
// loop through object
for (var i in object) {
// check if the extended object has that property
if (object.hasOwnProperty(i)) {
// mow check if the child is also and object so we go through it recursively
if (typeof this[i] == "object" && this.hasOwnProperty(i) && this[i] != null) {
this[i].extend(object[i]);
} else {
this[i] = object[i];
}
}
}
return this;
};
var options = {
foo: 'bar',
baz: 'dar'
}
var defaults = {
foo: false,
baz: 'car',
nat: 0
}
defaults.extend(options);
// defaults will now be
{
foo: 'bar',
baz: 'dar',
nat: 0
}
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
}
/* Instantiate the class. */
var alice = new Person('Alice', 93);
var bill = new Person('Bill', 30);
alice.displayGreeting = function()
{
alert(this.getGreeting());
}
Person.prototype.getGreeting = function()
{
return 'Hi ' + this.getName() + '!';
};
var k = {
name : 'jack',
age : 30
}
k.gender = 'male'; /*object or json k got extended with new property gender*/
function extend(object) {
if (object === null)
throw TypeError;
if (typeof object !== "object" && typeof object !== "function")
throw TypeError;
if (Object.create)
return Object.create(object);
function f() {}
;
f.prototype = p;
return new f();
}
var Person{
//some code
extend: extendProperty
}
//Enforce type checking an Error report as you wish
function extendProperty(object) {
if ((object !== null && (typeof object === "object" || typeof object === "function"))){
for (var prop in object) {
if (object.hasOwnProperty(prop))
this[prop] = object[prop];
}
}else{
throw TypeError; //Not an object
}
}