About the direction of this;

the point to this in the constructor

related codes

I"ve been reading js advanced programming recently, which is a little confusing.

in ordinary functions, this points to global scope:
var name = "moon";
function sayName () {

var name = "star";
console.log(this.name); //moon

}

but in the constructor, who is this pointing to:
function Person (name, age) {

this.name = name; //
this.age = age;

}
var p1 = new Person ("sun", 22);

The

book says: assign the scope of the constructor to the new object, so this points to the new object. Why the first case this is global scope, while the second case is functional scope? solve the puzzle

Apr.26,2021

just for the two examples in your title, this can only be determined at run time: depending on what object they are bound to when they execute, that this refers to that object.

    The
  1. sayName function,
    if you execute it directly, it is equivalent to global execution and is bound to the window object by default (strict mode is not discussed here), so this is window. var name= "moon" is defined globally, so it is an attribute of window, equivalent to window.name= "moon" .
    if you execute sayName.call ({name: 'sun'}), that is, the sayName binding is executed on the object {name:' sun'}, then this is the sun object.
  2. After the

    new operator is executed, an empty object {} is created, which is then similar to the execution of

    var newObj = {}; 
    Person.call(newObj, name, age);
    var pi = newObj;

    of course, new does not only do that, but also sets up the prototype chain, which is outside the scope of this issue.

Menu