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
由于某种原因,我没有收到警报,而是收到此错误:
未捕获TypeError:对象[object Object]没有方法'test'
答案 0 :(得分: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'
答案 1 :(得分: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();
答案 2 :(得分:0)
您必须将测试方法添加为init的原型。像这样......
var myclass = {
init:function () {
this.customer = null;
},
test : function(data){
alert(testing);
},
};
myclass.init.prototype = myclass;
这样所有对象都将继承自myclass对象。