0

我有一个像下面这样的构造函数

 var Example = (function () {
   function Example(opt) {
     this.opt = opt;
     return{
        function(){ console.log(this.check()); } // Here is an Error
     }   
   }
   Example.prototype.check = function () {
     console.infor('123');
   };
   return Example;
 }) ();

 var ex = new Example({ a:1 });

我知道我做错了,但无法弄清楚如何做到这一点。我想在对象返回中使用原型方法。请帮助我。

4

2 回答 2

2

如果你想check()在构建实例时运行,为什么不在构造函数中调用它呢?

var Example = (function () {
  function Example(opt) {
    this.opt = opt;
    this.check(); //this gets called when instances are made
  }
  Example.prototype.check = function () {
    console.infor('123');
  };
  return Example;
}) ();

//so `ex` is an instance of the Example Constructor
//and check gets called when you build it
var ex = new Example({ a:1 });
于 2013-06-06T03:30:07.357 回答
1

看着

function Example(opt) {
    this.opt = opt;
    this.check()
}
Example.prototype.check = function () {
    console.info('123');
};
于 2013-06-06T03:32:37.190 回答