Jump to content

Instance...[Solved]


eTianbun

Recommended Posts

Is it possible to create an Instance of another Instance of an Object?ex:

//create an instance of Object-->a=new Object();a.name="Ben";//create an instance of a>-->b=new a;alert(b.name) 

Is it posible to do this? will object b, inherit the property from object A?

Link to comment
Share on other sites

a needs to be a function, and any predefined values need to be inside the function:

var a = function() {  this.name = "Ben";} var b = new a();alert(b.name);

Link to comment
Share on other sites

If you want to clone an object, you'll have to loop through all the object's properties using a for...in loop and assign the values to the new object's properties.

Link to comment
Share on other sites

hmmm! :-\

var a=new Object();a.name="Ben";a.age=undefined;var b=new Object();pPos=0;for(properties in {b[pPos]=properties; pPos++}

you mean something like that? But that will be an array wright? Sorry if my code is incorrect, i usualy use mobile device(s) to access the NET, so i dont normaly test (debug), before i post! EDIT: By-the-way, if the object have a method, what will happen? Will the for...in execute it?

Link to comment
Share on other sites

No, methods won't be executed. Everything in the for...in loop is treated as a reference (which also means that arrays and objects inside the object won't be cloned, just referenced)

var a = new Object();a.name = "Ben";a.age = 20; var b = new object();for(propertyName in a) {  if( !(propertyName in Object.prototype) ) {    b[propertyName] = a[propertyName];  }}

Link to comment
Share on other sites

Kinda confusing! I see a condiction statement in the for...in. Can you write a short note on vat? I dont realy understand that part!
Yeah, I should have explained that. The object has a series of properties that are read-only or are set by the browser, like the "constructor" property, so when copying properties, you need to make sure that the property isn't part of the object's prototype.
Link to comment
Share on other sites

No. There are two ways to get a property's value: a.name or a["name"] The second one allows you to dynamically access properties:

var propertyName = "name";alert(a[propertyName]) // This displays the value of a.name

When copying an object, you copy the value of a property to the property of the same name:

b.name = a.name; OR b["name"] = a["name"] OR var propertyName = "name";b[propertyName] = a[propertyName]

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...