What types of objects should be stored as variables in JavaScript?

Two jsperfs related to the question:
Cache-ing 'this'
Logical Boolean

I'm on Mac 10.9. On Safari 7, Chrome 32, and Firefox 26, saving 'this' inside a variable seems to be a little slower than not storing it. For example:

function O() {
        var THIS = this;

        THIS.foo = 'foo';
        THIS.bar = 'bar';
        THIS.baz = 'baz';
}

was a bit slower than:

function O() {
    this.foo = 'foo';
    this.bar = 'bar';
    this.baz = 'baz';
}

Why is this? Is it because 'this' refers to the source object every time?

In Chrome and Firefox, storing a Boolean object and then referencing the value of this variable later seemed to work a little faster than writing “true” or “false” each time (theoretically creating a new Boolean object each time.) BUT, in Safari the opposite happened the truth. For example:

function lt() {
    if(arguments[0] < arguments[1]) return true;
    return false;
}

was slightly faster (in Firefox and Chrome) than:

var TRUE = true,
    FALSE = false;

function lt() {
    if(arguments[0] < arguments[1]) return TRUE;
    return FALSE;
}

Safari, , , ? , ?

, , , , - , . , .

​​jsperfs - . , , , JS. ?

+4
2

, - Firefox Chrome , , ; . , ECMAScript:

, this , . , - - ( , ):

{ this: caller, THIS: caller };
// this: system-created property (?during function object creation or invocation?)
// caller: system-initialized value, during invocation
// THIS: user-created-and-initialized property, slows down execution

, , , , . , , , . . , , .

- . - () . :.

var obj0, obj1, funExt;
obj0 = {};
obj1 = {};
funExt = (function () {
    var cachedId, cachedObj;
    // After evaluation of funExt is done these values will persist in closure,
    // avoiding value creation during the execution of returned function.
    cachedId = "extension";
    cachedObj = { prop0: myValue, prop1: myValue, prop2: myValue };
    return function (o) {
        if (o) {
            o[cachedId] = cachedObject;
        } else if (this !== window) {
            o = (this[cachedId] = cachedObj);
        }
        return o;
    };
}());
obj0.funExt();
funExt(obj1);

, , Chrome Firefox , . , .

, javascript- " ". , , . . , , , . , .

0

, , . , this , foo.bar.something.else.x , , , . , .

, . , 4 , , .

0

Source: https://habr.com/ru/post/1526085/


All Articles