I have two objects of the same type.
function myObject(){
this.a = 1;
this.b = 1;
function changeA(){//some code};
function changeB(){//some code};
}
var obj1 = new myObject();
var obj2 = new myObject();
How can I make a call to obj2.changeB() from external code, another function or another object (e.g. obj1) ?
3 Answers 3
obj2.changeB() doesn't exist.
You need to assign a property on your object, not create a local variable:
this.changeB = function() { ... };
answered Sep 7, 2014 at 14:51
SLaks
891k182 gold badges1.9k silver badges2k bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Just create a properties in you object like:
function myObject(){
this.a = 1;
this.b = 1;
this.functionA = function changeA(){//some code
alert('im 1');
};
this.functionb = function changeB(){//some code
alert('im 2');};
}
and call the function obj2.functionb();
answered Sep 7, 2014 at 14:53
Wilfredo P
4,07430 silver badges46 bronze badges
Comments
You have to do something like that:
var myObject = function(){
var protectedValue1 = ‘variable’;
var protectedValue2 = ‘variable’;
var changeA = function(){
alert(protectedValue);
}
var changeB = function(){
alert(protectedValue);
}
}
var object1 = new myObject();
var object2 = new myObject();
//
object2.changeB();
answered Sep 7, 2014 at 14:56
Giannis Grivas
3,4242 gold badges22 silver badges40 bronze badges
Comments
lang-js
myObject