2013-07-26 4 views
0
var myclass = { 
    init:function() { 
     this.customer = null; 
    }, 
    test : function(data){ 
     alert(testing); 
    } 
}; 

Я инстанцировании myclass как выше, а затем я пытаюсь вызвать метод test класса, но он не работает. Что я делаю не так?Невозможно вызвать метод после создания экземпляра класса

var testClass = new myclass.init(); 
testClass.customer = 'John B'; 
testClass.test(); //doesnt alert 1 

Вместо того, чтобы получать предупреждения, по какой-то причине, я получаю эту ошибку:

Uncaught TypeError: Object [object Object] has no method 'test'

+0

вы должны быть используя класс как имя переменной? – gezzuzz

+0

Просто указывая. class - зарезервированное ключевое слово в JS. Возможно, вы захотите использовать что-то вроде clazz – mohkhan

+0

Я изменил класс на testClass .. все равно – Autolycus

ответ

0

Вы должны добавить метод испытания прототип инициализации. Как это ...

var myclass = { 
    init:function() { 
     this.customer = null; 
    }, 
    test : function(data){ 
     alert(testing); 
    }, 
}; 

myclass.init.prototype = myclass; 

Таким образом, все объекты наследуются от объекта myclass.

+0

Это работает, но выглядит так неправильно ... – bfavaretto

4

Вы должны определить свой «класс» как функцию конструктора, а не объект буквальным:

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' 

Тогда функция init не действительно необходимо, вы можете добавить, что логика в самом конструкторе:

var MyClass = function(){ 
    this.customer = null; 

    this.test = function(data){ 
     alert('testing'); 
    }; 
}; 
var testClass = new MyClass(); 
testClass.customer = 'John B'; 
testClass.test(); //alerts 'testing' 

Вы также можете добавить свои методы в MyClass.prototype вместо объявления их внутри конструктора. Для разницы между ними см. Use of 'prototype' vs. 'this' in JavaScript?.

Наконец, если вы хотите придерживаться вашего объекта буквального, вы должны использовать 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' 
2

другую реализацию, с некоторыми пояснениями:

var MyClass = function() { 
    this.customer = null; 
}; 

// Any functions need to be added to the prototype, 
// and should use the keyword this to access member fields. 
// Doing this allows for a performance gain over recreating a new function definition 
// every time we create the object, as would be the case with this.test = function() { ... } 
MyClass.prototype.test = function(data){ 
    alert('testing'); 
}; 

// At this point, MyClass is a constructor function with all of it's 
// prototype methods set, ready to be instantiated. 

var testClass = new MyClass(); 
testClass.customer = 'John B'; // May also want to consider moving this into the constructor function as a parameter. 
testClass.test(); 

JSFiddle

Смежные вопросы