In the wechat group, I saw someone send out a Javascr interview question. I was very interested in comparing dishes and immediately began to masturbate.

function Foo() {
  getName = function() {console.log(1)}
  return this
}
Foo.getName = function() {console.log(2)}
Foo.prototype.getName = function() {console.log(3)}
var getName = function() {console.log(4)}
function getName() {console.log(5)}

Foo.getName()
getName()
Foo().getName()
getName();
new Foo.getName()
new Foo().getName()
new new Foo().getName()
Copy the code

Take a preliminary look: this topic involves a lot of knowledge points or containThe investigation of these points of knowledge

Step 1: Since Js is single threaded, the code is executed line by line, but becauseVariable ascensionWe can conclude that

function Foo() {
  getName = function() {console.log(1)}
  return this
}
+ var getName
+ function getName() {console.log(5)}

Foo.getName = function() {console.log(2)}
Foo.prototype.getName = function() {console.log(3)}

- var getName = function() {console.log(4)}
- function getName() {console.log(5)}
+ getName = function() {console.log(4)}... omitCopy the code

Function getName() {console.log(5)} function getName() {console.log(5)}

Step 2: See what happens when the program executes to foo.getName ()

function Foo() {
  getName = function() {console.log(1)}
  return this
}
+ var getName
+ function getName() {console.log(5)}

Foo.getName = function() {console.log(2)}
Foo.prototype.getName = function() {console.log(3)}

- var getName = function() {console.log(4)}
- function getName() {console.log(5)}
+ getName = function() {console.log(4)}... omitCopy the code

Function getName() {console.log(4)} function getName() {console.log(4)}

Step 3: At the end of foo.getName (), the output is 2

Step 4: At the end of getName(), the output is 4

Step 5: At the end of the program execution Foo().getName(), the output is 1

function Foo() {
  getName = function() {console.log(1)}
  return this}... Omit the Foo (). The getName ()... omitCopy the code

Foo is called because getName in Foo scope is not declared by var, so getName is a global variable, Function () {console.log(1)} and because Foo() returns this, Foo() is an implicit call to window.foo (), so this is window. window.getName() => 1

Step 6: At the end of getName(), the output is 1

Step 7: At the end of new foo.getName (), the output is 2

function Foo() {
  getName = function() {console.log(1)}
  returnthis } ... Omit new foo.getName ()... omitCopy the code

New foo.getName () = new (foo.getName)();

Step 8: At the end of new Foo().getName(), the output is 3

New Foo().getName() equals (new Foo().getName()

Step 9: At the end of new new Foo().getName(), the output is 3

New new Foo().getName() = new ((new Foo()).getName)()

Js primitive operator priority summary table


[Study notes, any mistakes, please advise, thank you for reading! 😊]

If you help, please click a like, thank you! 😊