简体   繁体   English

JavaScript中的原型/类/公共属性

[英]Prototype / class / public attributes in JavaScript

I have a constructor for a model (similar to Backbone model) which uses an instance of a store (eg MongoDB / Redis) which is passed to the model factory. 我有一个模型的构造函数(类似于Backbone模型),它使用存储实例(例如MongoDB / Redis)传递给模型工厂。 Now inside the constructor for the model, I do 现在在模型的构造函数中,

this.store = options.store; 

Store is now available as this.store once I construct an instance with var model = new Model() . 现在,当我使用var model = new Model()构造实例时,Store现在可以作为this.store使用。

Then I faced a situation when I my Model has "public" methods, eg Model.find() which will work without instantiating the model. 然后,当我的模型具有“公共”方法时,例如Model.find() ,该方法无需实例化模型即可工作。 But now because it's not been instantiated, functions inside Model can not access store by this.store . 但是现在,由于尚未实例化,因此Model。内部的函数无法通过this.store访问store。

What I did, is I started also adding store to the constructor itself Model.store = options.store which fixes the problem. 我所做的是,我也开始将store添加到构造函数本身中, Model.store = options.store可以解决此问题。 But now store is exposed to anything that uses Model constructor and this is not desirable. 但是现在商店暴露给使用Model构造函数的任何事物,这是不希望的。

I am guessing I am doing something wrong. 我猜我做错了什么。 So I would appreciate some help. 因此,我将感谢您的帮助。

If I get what you're saying correctly, then I think what you want is to allow for a "static" find() method on Model without exposing the store variable. 如果我正确地理解了您的意思,那么我想您想要的是允许在Model上使用“静态” find()方法而不暴露出store变量。 Javascript doesn't really have a formal private scope for classes, but you can get what you want using closures. Javascript实际上并没有正式的类私有范围,但是您可以使用闭包来获得所需的内容。 Here's a fiddle: 这是一个小提琴:

http://jsfiddle.net/52FPy/ http://jsfiddle.net/52FPy/

EDIT: An updated fiddle to demonstrate various ways to expose/hide info using closures: http://jsfiddle.net/52FPy/2/ 编辑:一个更新的小提琴,演示了使用闭包公开/隐藏信息的各种方法: http : //jsfiddle.net/52FPy/2/

Briefly: 简述:

var Model = function(){
    var store = 'this is a store';
    var Model = function(){

    }

    Model.find = function(){
        return store;
    }

    return Model;
}()

This will "hide" the store variable in the way you want. 这将以您想要的方式“隐藏” store变量。

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

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