w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
change "var" inside constructor closure where new instance is created

The issue here is that the _self variable you assign to in instance A (and B) is not the same _self variable from function c scope, it is a global variable (in the window object)

var c = function(obj){
    var _self = this; // scope of function 'c'
    this.name = "lol";
    this.init = function(){
        _self = this; // still scope of function 'c'
    this.sayName = function(){
        console.log(_self.name); // scope of function 'c'

var A = new c({
    name : "A",
    init : function(){
        _self = this; // global scope here, _self === window._self
    sayA : function(){
        console.log(_self.name) // also call to the global _self object


This way objects A and B both use window._self in their functions, therefore making them share data. The thing to learn from here is that you cannot manipulate variables that are defined in the function scope with the 'var' declaration. The ones you can manipulate you have to assign to 'this' (in case of constructors)

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.