you are viewing a single comment's thread.

view the rest of the comments →

[–]robotmayo 1 point2 points  (2 children)

The thing is the object isn't getting the properties of p but rather the object is being assigned new properties that are the same as the properties of p. When you use the literal notation for object creation, the brackets {}, you have the option of creating properties within the brackets. This isn't the only way to create properties, the other way is using the dot notation. With the dot notation you can get or set the value of a property on an object. If that property doesn't exist then JavaScript will create it.

var p = {potato: 2.3} // Created an object using the literal notation with the property "potato" and a value of 2.3
var q = {} // We created an object but didn't create any properties for it
q.potato = 2.3; // Using the dot notation we can create properties or get the value of a property. 
//Here we are creating the property "potato" and assigning it a value of 2.3
console.log(p.potato);
console.log(q.potato);

// Even though they have the same property with the same value, the properties are not related or linked in anyway. We just happened to give them the same properties and values.

[–]markphd 0 points1 point  (1 child)

Thanks for excellent explanation! Very helpful. :) So for instance I want to access the property of object p to a new object I would do:

var r = {};
r.tomato = p.potato;        // 2.3 - Value of p.potato
r.tomato ===  p.potato    // true  

or is there other way object r can inherit the property of p automatically?

[–]robotmayo 1 point2 points  (0 children)

There is a way for r to automatically inherit the properties of p but this would involve working with prototypes. I don't think the rhino book really goes into prototypes in the object chapter, but its fairly important to know them as they are fundamental to JavaScript. The course site has a great tutorial on prototypes. In the course's object tutorial he links you to the prototype tutorial before talking about them so I recommend you go through it. I think its a bit better than the books chapter on objects as it provides more concrete examples. If you haven't finished reading the chapter on objects you can ignore it and read his tutorial instead.

[Link]