Skip to content

this 和 javascript执行问题 #150

@adnabb

Description

@adnabb

问题记录:
(1)

	it('bind undefined', function () {
      var obj = {
        say: function () {
          function _say() {
            // this 是什么?想想为什么?
            this.should.equal(global)
          }
          return _say.bind(obj)
        }()
      }
      obj.say()
    })

在正在定义obj的时候,say就立即执行了,此时的 this 为 global, 此时的obj不存在

当obj.say()执行的时候,obj已经存在了,可是为什么 this 的指向还是 global?

同样的(后者可以理解),

it('bind normal', function () {
  var obj = {}
  obj.say = function () {
    function _say() {
      // this 是什么?想想为什么?
      this.should.equal(obj)
    }
    return _say.bind(obj)
  }()
  obj.say()
})

在给obj赋值的时候,say立即执行了,此时的 this 指向 obj

当obj.say()执行的时候,obj一直存在,this 仍然指向 obj

(2)执行问题

测试用例里面的调用其实不是obj.say()函数,而是obj在定义时执行的函数?

然后obj.say()调用的是下面的紫色的函数吗?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions