Home > Enterprise >  Can anyone help me to undrstnd the output of the below code
Can anyone help me to undrstnd the output of the below code

Time:11-21

  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

CodePudding user response:

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

CodePudding user response:

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

  • Related