You have to define your "class" as a constructor function, not an object literal:
var MyClass = function(){
this.init = function () {
this.customer = null;
};
this.test = function(data){
alert('testing');
};
};
var testClass = new MyClass();
testClass.init();
testClass.customer = 'John B';
testClass.test(); //alerts 'testing'
Then the init
function is not really needed, you can add that logic to the constructor itself:
var MyClass = function(){
this.customer = null;
this.test = function(data){
alert('testing');
};
};
var testClass = new MyClass();
testClass.customer = 'John B';
testClass.test(); //alerts 'testing'
You can also add your methods to MyClass.prototype
instead of declaring them inside the constructor. For the difference between the two, refer to Use of 'prototype' vs. 'this' in JavaScript?.
Finally, if you want to stick to your object literal, you have to use Object.create
:
var myclass = {
init:function () {
this.customer = null;
},
test : function(data){
alert('testing');
}
};
var testClass = Object.create(myclass);
testClass.customer = 'John B';
testClass.test(); //alerts 'testing'