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

出于某种原因,我没有收到警报,而是收到此错误:

未捕获的类型错误:对象 [对象对象] 没有方法“测试”

4

3 回答 3

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而不是在构造函数中声明它们。两者的区别,请参考JavaScript 中使用 'prototype' 与 'this'?.

最后,如果你想坚持你的对象文字,你必须使用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'
于 2013-07-26T21:37:15.383 回答
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

于 2013-07-26T21:41:54.943 回答
0

您必须将测试方法添加为 init 的原型。像这样...

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

myclass.init.prototype = myclass;

这样所有对象都将继承自 myclass 对象。

于 2013-07-26T21:36:02.090 回答