An interview question for js

topic description

var obj = {
   name:"zhangsan",
   sayName:function(){
     console.info(this.name);
   }
 }
 var wfunc = obj.sayName;
 obj.sayName();//zhangsan
 wfunc();//undefined
 var name = "lisi";
 obj.sayName();//zhangsan
 wfunc();//lisi

sources of topics and their own ideas

is mainly because I don"t know the reasons for the next three answers. I hope the boss can explain

.
Jul.06,2022

the second is not undefined, but an empty string. Window comes with the name attribute


my understanding is:
/ declare variables first:
var obj,
var wfunc,
var name,
/ in the assignment
var obj= {}
var var wfunc = obj.sayName;
obj.sayName () / / this takes the value of name as zhangsan
wfunc () / / the this at this time points to the declared name in window,window, but is not defined, so this time is undefined
name= "lisi" / / at this time the name value is lisi
obj.sayName () / / this points to obj, so the value of name is zhangsan
wfunc () / / at this time this points to the name declared in window,window, and is assigned to lisi


when calling with obj , the object context of sayName is obj .
is re-assigned to wfunc before execution. The context object is window , but there is no name attribute on window . In addition, variables declared using var are promoted to global variables and are mounted under the window object by default, so the context object is still window , but the name attribute already exists.


var wfunc = obj.sayName;   
//wfunc
wfunc = function () {
    console.log(this.name)   //thiswindow
} 
undefined

obj.sayName (); / / zhangsan / / this points to obj

var name = "lisi";    //window.name = 'lisi'
obj.sayName();//zhangsan
wfunc();//lisi    
Menu