简体   繁体   English

JavaScript原型的构造方法

[英]Constructor for prototype in Javascript

In file meterA.js I have this 在meterA.js文件中我有这个

    window.MeterA = function(options)
    {
        return this.init(options);
    }

   MeterA.prototype = {
        init: function(options) {
            this.container = options.container;
            this.width = options.width;
            this.height = options.height;
            this.sliderSize = options.sliderSize;
            var Canvas = {
                meter: TBE.CreateRectCanvasElement (displayWidth, displayHeight),
                slider: TBE.CreateSquareCanvasElement (sliderSize)
            };
            Container.appendChild (Canvas.meter);
            Container.appendChild (Canvas.slider);
        }
    }

Then in file pane.html, I tried to initialise meter with: 然后在文件pane.html中,我尝试使用以下方法初始化电表:

var MeterA = new MeterA({
    container:  Div.meterA, 
    width:      GetNumberIgnoreUnit(Div.speedMeter.style.width, 2), 
    height:     GetNumberIgnoreUnit(Div.speedMeter.style.height, 2), 
    sliderSize: 10
});

But I get "MeterA is not a constructor" as error, why is it? 但是我收到“ MeterA不是构造函数”错误,为什么?

var MeterA = new MeterA({ ...

I believe using MeterA as the variable name and the class name is the problem here. 我相信使用MeterA作为变量名和类名是这里的问题。 Variable declarations in Javascript are "hoisted" to the top of the function so MeterA becomes undefined Javascript中的变量声明被“提升”到函数的顶部,因此MeterA变得未定义

Some good explanation here : http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/ 这里有一些很好的解释: http : //net.tutsplus.com/tutorials/javascript-ajax/quick-tip-javascript-hoisting-explained/

Smth along these lines should work : 这些方面的东西应该起作用:

var MeterA = (function () {

    // constructor
    var MeterA = function (options) {
        this.init(options);
    };

    // prototype
    MeterA.prototype = {
        init: function (options) {
            console.log(options);
        }
    };

    return MeterA;

})();

obj = new MeterA({
    opt1: 'sasa',
    opt2: false
});

I recomend Javascript Patterns 2010 for a more in-depth overview of the constructor pattern . 我推荐Javascript Patterns 2010 ,以更深入地了解构造函数模式。

Another good read about javascript Essential JavaScript Design Patterns For Beginners, Volume 1. 关于初学者的 javascript 基本JavaScript设计模式的另一本好书,第1卷。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM