JavaScript new keyword and objects scopes

后端 未结 1 1720
有刺的猬
有刺的猬 2021-01-06 20:29

Later today, I was scrolling through ejhon.com slides and I found out the following:

Give this code

function katana () {
this.myvar = true;
}
katana          


        
相关标签:
1条回答
  • 2021-01-06 21:15

    When you say new katana(), Javascript calls the katana function, with a new blank object as this. Once it returns, presumably initialized, the new object (or whatever katana returns, as long as it's an object) is set up so that its 'prototype' (the object that it'll inherit fields and such from) is the same as the katana function's prototype.

    Yeah, that didn't make much sense either the first time i went through it. The oversimplified version is, you say new katana(), and Javascript creates what'll be a katana instance and lets the katana function initialize it. You say katana(), and this is basically the last object in the call stack to have been used in an instance method call. (If your caller was x.foo, this == x.) If there's no such object, seems this is the same as window.

    As for why xyz isn't showing up, you declared the variable with var. That changes the scope. If you got rid of that, you'd see a window.xyz.

    0 讨论(0)
提交回复
热议问题