Hammer Hammer - 4 months ago 17
Javascript Question

Javascript Module inheritence

Parent Module,

var Component = function () {
var _componentName;
var _test = 'ts';
return {
getName: function(){
console.log('getName() is called');
console.log(this._componentName);
console.log(_test);
return _componentName;
}
};
};

module.exports = Component;


Child module,

var Component = require('./component');

var Skip_button = function () {
var skipBtn = Component();
skipBtn._componentName = 'Skip_Btn';
return skipBtn;
};

module.exports = Skip_button;


In another place, when I call

var skipBtn = Skip_button();
skipBtn.getName();


if it is
console.log(this._componentName);
in Component, the value can be printed out successfully. However, if it is
console.log(_componentName);
, undefine error will be there. Any idea?

[Update]
Check this out. It works as expected. http://jsfiddle.net/nedvedyy/Lvxqjo9v/1 so the question is still, why it does not work in my original code example above if
console.log(this._componentName);
is changed to
console.log(_componentName);

Answer

In Component funtion _componentName and _test are not in the this scope. but however you are setting skipBtn._componentName in the Skip_button function means you are setting _componentName in the this scope. thats why console.log(this._componentName) printing 'Skip_Btn'

var Component = function () {
    var _componentName;
    var _test = 'ts';
    return {
        getName: function(){
            console.log('getName() is called');
            console.log(this._componentName);
            console.log(this._test);
            return _componentName;
        }
    };
};

var Skip_button = function () {
    var skipBtn = Component();
    skipBtn._componentName = 'Skip_Btn';
    return skipBtn ;
};

var skipBtn = Skip_button();
skipBtn.getName();

If you run the above script this._test will print 'undefined' becuase _test is not in the this scope.

var Component = function () {
        var _componentName = 'test';
        var _test = 'ts';
        return {
            getName: function(){
                console.log('getName() is called');
                console.log(_componentName);
                console.log(_test);
                return _componentName;
            }
        };
    };

    var Skip_button = function () {
        var skipBtn = Component();
        skipBtn._componentName = 'Skip_Btn';
        return skipBtn ;
    };

    var skipBtn = Skip_button();
    skipBtn.getName();

If you run the above code, console.log(_componentName) will print 'test' becasue it has some value

Comments