以正确的方式设计课程

Jus*_*ago 5 javascript oop

我有一些关于JavaScript的问题,我需要确定.为了帮助,我有一个简单的类定义我正在写:

var dataSource = function (src, extension) {
    return {
        exists: function () {
            // function to check if the source exists (src *should* be an object
            // and extension should be a string in the format ".property.property.theSource".
            // this function will return true if src.property.property.theSource exists)
        },
        get: function () {
            // function will return the source (ex: return src.property.property.theSource)
        }
    }   
}();
Run Code Online (Sandbox Code Playgroud)

问题:

1)在我目前对JavaScript的理解中,调用dataSource()将创建一个具有自己的exists()和get()方法副本的新对象.我对么?

2)有没有办法写这个,这样如果我创建1,000,000个dataSource对象,我只需要每个函数的一个副本?

3)我是否应该关注(2)?

tob*_*ies 7

你有一个函数返回Object的istance,而不是JS类.

您将需要签出使用DataSource.prototype,this如果要将其与结合使用,则应在构造函数中添加属性或进行修改.new

你可能应该做这样的事情:

function DataSource(src, extension){
    //Make sure this behaves correctly if someone forgets to use new
    if (! this instanceof DataSource)
         return new DataSource(src,extension);
    //store the constructor arguments
    //so you can use them in the shared methods below
    this._src=src;
    this._extension=extension;
}
DataSource.prototype.exists=function(){
    //use this._src and this._extension here
    //This method will be available to all
    //objects constructed by new DataSource(...)
};
DataSource.prototype.get=function(){
    //use this._src and this._extension here
    //This method will be available to all
    //objects constructed by new DataSource(...)
};

var instance = new DataSource('a source','an extension');
Run Code Online (Sandbox Code Playgroud)

编辑: 您提到过您更喜欢'私人'变量

构造闭包是模拟私有属性的唯一可移植方式,但是根据我的经验,在_组织中加上一个并且在组织中具有约定而不依赖于_前缀变量的约定在大多数情况下就足够了


Pau*_*l S 5

原型是你想要使用的.它将被存储一次并与对象的所有实例相关联.