Advertisement
Guest User

Untitled

a guest
May 26th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. // Method 1: We'll define a constructor functoin and create an object using the new keyword. Then, we'll create another object and see how we can access its peoperties using the first object
  2. function Person (name, age) {
  3. this.name = name;
  4. this.age = age;
  5. }
  6.  
  7. var person1 = new Person ("Mark", 25) // defined an object called person1 using the Person constructor function above
  8. var person2 = {nationality: "Australian"} // defines a simple object literal with a nationality key
  9. // Now to let person1 access person2's nationality, we can use the same setPrototypeOf method:
  10. Object.setPrototypeOf(person1, person2) // same as the cat and dog example above
  11. person1.nationality // returns 'Australian' as expected
  12.  
  13. // Method 2: If we do the same thing but instead, we set the prototype of the constructor function to person2's prototype, we can now only access it via the constructor object:
  14. var person1 = new Person ("Mark", 25)
  15. var person2 = {nationality: "Australian"}
  16. Object.setPrototypeOf(Person, person2) // we've replaced person1 with Person
  17.  
  18. person1.nationality // returns 'undefined', because person1 can access person2's properties only via the constructor object, as follows:
  19. person1.constructor.nationality // returns "Australian"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement