3

class Obj {
  static log(){
    console.log(this)
  }
}

var test = Obj.log

Obj.log() // class Obj
test() // undefined

This is the code I run without 'use strict'. The result I don't understand. Why does the function test log undefined instead of the global object?

2
  • What did you expect it to return? Commented Mar 25, 2017 at 8:08
  • 1
    The window object like the simple function. Commented Mar 25, 2017 at 8:09

1 Answer 1

6

It's because class code is always strict code. From the spec

NOTE     A class definition is always strict code.

Since class code is always strict, the method log is a strict function (so amongst other things, its internal [[ThisMode]] slot is set to strict), and when you call a strict function without setting this, this is set to undefined for the call.

The chain of operations in the spec that sets this up is that a direct call expression is evaluated by eventually calling the spec's abstract EvaluateDirectCall operation with thisValue set to undefined. That in turn calls Call passing along the thisValue, which calls [[Call]] on the function passing thisValue as thisArgument, which calls OrdinaryCallBindThis, which checks the function's [[ThisMode]] and, if it's strict, sets the thisValue to thisArgument directly without further logic (whereas if it weren't strict, it would replace null and undefined with the global object and do ToObject on any other values).

Sign up to request clarification or add additional context in comments.

2 Comments

OrdinaryCallBindThis ( F, calleeContext, thisArgument ). test.call(obj, list). In this situation, F means test, calleeContext means obj, thisArgument means list. Is this right?
@李晓爽: No. F is test and thisArgument is obj. The calleeContext is the execution context created by [[Call]]'s call to PrepareForOrdinaryCall. (My link to [[Call]] above was wrong, btw, I've fixed it.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.