skip to Main Content

I would like to run this code but its giving me output of undefined in second console log instead of Oracle as I’m trying to call it from var retrieve name with reference to global var and this keyword.

this.name = "Oracle";
var website = {
name: "Java",
getName: function () {
return this.name;
   },
 };

console.log(website.getName()); // Java

var retrieveName = website.getName; //
console.log(retrieveName()); // Oracle but its printing undefined

var boundGetName = retrieveName.bind(website);
console.log(boundGetName()); // Java

2

Answers


  1. Chosen as BEST ANSWER

    [output received][1]

    I was running the code in Node.js that's why it seems to provide error on global var access. Now I made to run in Sloppy mode then ALL CLEARED..


  2. It is not the same, if you declare function, or value.

    var website = {
    name: "Java",
    getName: function () {
    return this.name;
       },
     };
    
    console.log(website.getName()); // Java
    
    var retrieveName = website.getName(); //
    console.log(retrieveName); // Java
    
    website.name='Oracle';
    
    var boundGetName = website.getName.bind(website);
    console.log(boundGetName()); // Oracle
    

    Set this.name outside of an object is incorrect using of this.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search