Can anyone help me to undrstnd the output of the below code

Can anyone help me to undrstnd the output of the below code

Problem Description:

  let obj1 ={
    fName : 'Ayush',
    lName : 'Singh',
    city: 'Asansol',
    getName : function(){
      console.log(`I am ${this.fName} ${this.lName} from ${this.city}`)
    }
  }
  let obj2 = {
    fName : 'Aman'
  }

  obj2.__proto__ = obj1;

  console.log(obj1.getName())
  obj2.getName()
  console.log(obj2.__proto__.getName())
  console.log(obj1.__proto__.getName())

Here I am trying to check how proto works. Why can’t I access of obj1.proto.getName

Solution – 1

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

how proto work is it as getter and setter of object.

why your obj1.proto doesnot work because you have not set it. you only set it for obj2.

more ref from docs :-

Object.prototype.proto

Solution – 2

obj2.getName():
it look inside obj2 for "getName" method but not found here, so it look at the prototype of obj2 which is obj1, there is a method call "getName" here

obj2.proto.getName() = (obj2.proto).getName() = obj1.getName()

obj1.proto.getName() You are not calling "getName" method inside obj1, you are calling the "getName" method inside the prototype of obj1, but it is not found here

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject