Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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
- function Person (name, age) {
- this.name = name;
- this.age = age;
- }
- var person1 = new Person ("Mark", 25) // defined an object called person1 using the Person constructor function above
- var person2 = {nationality: "Australian"} // defines a simple object literal with a nationality key
- // Now to let person1 access person2's nationality, we can use the same setPrototypeOf method:
- Object.setPrototypeOf(person1, person2) // same as the cat and dog example above
- person1.nationality // returns 'Australian' as expected
- // 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:
- var person1 = new Person ("Mark", 25)
- var person2 = {nationality: "Australian"}
- Object.setPrototypeOf(Person, person2) // we've replaced person1 with Person
- person1.nationality // returns 'undefined', because person1 can access person2's properties only via the constructor object, as follows:
- person1.constructor.nationality // returns "Australian"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement