在Javascript中定义构造函数时遇到问题

时间:2016-08-17 15:14:14

标签: javascript

我在common.js文件中有一个Javascript对象:

var KITS=
{
   debug: false,
   default_country : 'xxx',
   franchise : '' 
};

KITS.init=function(cb)
{
   var self = this; 
   $.ajax({
        // ...

            if (typeof cb==='function') (cb)();
        },
    }); 

   if (typeof cb==='function') (cb)();
 };

我将这个js文件包含在php文件中。有些专家可以告诉我需要做什么,以便在创建KITS对象时自动调用KITS.init()吗?

2 个答案:

答案 0 :(得分:0)

对象文字不是用new创建的,因此即使它们有构造函数也不会触发它。由于没有自己的原型,他们没有构造函数:

const foo = {
  a: 1,
  b: 2
};
console.log(Object.getPrototypeOf(foo));

答案 1 :(得分:0)

你需要真正的constructor

function KITS() {
    // This is contructor method
    console.log('hello world!');

    // Call your init method if you want
    this.init();
}
KITS.prototype = {
    constructor: KITS,
    init: function() {
        // Do some staff here
    }
};

var kits = new KITS();

工作示例https://jsfiddle.net/61feepq5/1/