Skip to content

04_AboutFunctionMethod.js에서 함수 메소드 관련 의문점 해결 #1

@Yeonlisa

Description

@Yeonlisa

04_AboutFunctionMethod.js 에 가면

describe('call에 관해서', () => {

  it('call의 첫번째 인자 값을 확인합니다', () => {
    function foo() {
      return this;
    }

    const context1 = { msg: 'welcome everyone' }
    const context2 = { msg: 'good bye' }

    expect(foo.call(context1)).to.eql({ msg: 'welcome everyone' })
    expect(foo.call(context2).msg).to.eql('good bye')
    expect(foo.call()).to.eql(global)
  })

이러한 문제가 있다.
여기서

    expect(foo.call()).to.eql(global)

왜 global이 되는지 이해가안갔다.
그러다가 this 관련해서 학습 중 이해를했다.

this는 함수 실행시 호출 방법에 따라 결정되는 특별한 객체인데,
이 중 Global또는 .call이나 .apply같은 Function로 호출할 수 있다.

여기서, Global과 Function 호출시 바인딩되는 객체는 브라우저 환경이냐 node.js 환경이냐에 따라 달라진다.

Global로 호출할때

브라우저 환경 node.js 환경
window module.exports

Function으로 호출할 때

브라우저 환경 node.js 환경
window global

vscode에서 실행하는 스프린트는 node.js 환경이다.(npm install했으니깐)
그래서 foo.call()이 global이 되는 것이다.

참고)
브라우저 환경(개발자콘솔)에서 위의 코드 실행시 화면캡쳐
스크린샷 2021-08-05 오후 5 59 32

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions