“var” variables, “this” variables and “global” variables - inside a JavaScript Constructor

[亡魂溺海] 提交于 2019-11-30 21:40:23

Just to focus on the scope, I'm going to run through this example, (with clearer variables) Afterwards, I'll connect it back to your variables.

var x = "Global scope";
var y = "Not changed.";

function Foo() {
    this.x = "Attribute of foo";
    var x = "In foo's closure";
    y = "Changed!"
    this.getX = function () { 
        return x;
    }
}

// do some logging

console.log(x); // "Global scope"
console.log(y); // "Not changed"
foo = new Foo();
console.log(y); // "Changed!"
console.log(foo.x); // "Attribute of foo"
console.log(x); // "Global scope"
console.log(foo.getX()); // "In foo's closure"

The line: this.x is equivalent to this.bla, and it defines an externally available attribute of a Foo object. y is equivalent to blablabla=100 and then the x within foo is equivalent to your blablabla within foo. Here's a really rough jsfiddle you can run to see this.

Everything you've said is correct. (Of course, an error will be thrown at the blablabla assignment in Strict Mode.

On the second half, there's nothing special about the constructor function. It just acts like any other function in that it creates a closure that persists as long as its referenced (the lifetime of this.getblabla in this case).

Take this example:

function initBlaBla() {
    var blabla = 10;
    this.getblabla = function () { 
        return blabla; // exposes blabla outside
    }
}

function Foo() {
    this.bla = 1;
    blablabla = 100;
    initBlaBla.call(this);
}

foo = new Foo();

Here, the Foo constructor doesn't form a closure and its scope gets released immediately. initBlaBla on the other hand creates a closure. Interestingly, the compiler may see that blabla is never written to and optimize this.getblabla to always return 10 and never save the closure scope. This can be seen when you break execution in a function inside a closure and try reading a value it doesn't internally reference.

The closure scope will get released and queued for garbage collection if you call any of the following:

delete foo.getblabla;
foo.getblabla = "Anything!";
foo = "Anything else.";

Yes, you understand it!
As for the second part of the question, it is all about inheritance, just like the relation between (global) window and the functions defined in it's scope (think root). So everything you do not re-specify, will be looked up at the ancestor.

This is a tremendous good video by Crockford, who explains it REALLY well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!