Joh*_*sen 4 javascript namespaces coffeescript
我想通过使用关键字"with"在javascript中使用命名空间,但CoffeeScript将此报告为保留关键字并且拒绝编译是否有任何方法可以在cs中使用命名空间?
特别是,我希望动态包含CoffeeScript文件(可信源),比如加载数据库模式的模型,但我希望包含的脚本能够访问本地名称空间.
编辑:
这就是我想要做的.我正在建立一个Web框架,它将目录树映射到基于express和mongoose的应用程序.例如,有一个子目录'models'包含一个文件'user.coffee',里面有这样的代码:
name:
type: String
unique: on
profiles: [ Profile ]
Run Code Online (Sandbox Code Playgroud)
Whereby Profile是一个位于名为的本地对象中的类model.加载用户模型时,我希望它能够访问位于我的本地模型商店中的模型类.
我现在的解决方法是写入model.Profile'user.coffee'文件.希望很清楚我的意思.
第二次编辑
以下是我不使用的方法with:
user.coffee
name:
type: String
unique: on
profiles: [ @profile ]
Run Code Online (Sandbox Code Playgroud)
profile.coffee
content: String
Run Code Online (Sandbox Code Playgroud)
以下是动态加载的方式:
for fm in fs.readdirSync "#{base}/models"
m = path.basename fm, '.coffee'
schema[m] = (()->
new Schema coffee.eval (
fs.readFileSync "#{base}/models/#{fm}", 'utf8'
), bare: on
).call model
mongoose.model m, schema[m]
model[m] = mongoose.model m
Run Code Online (Sandbox Code Playgroud)
对我来说似乎是一个好的解决方案.
让别人的意见强加于你?这是Hack Time™!
o =
a: 1
b: 2
c: 3
`with(o) {//`
alert a
`}`
Run Code Online (Sandbox Code Playgroud)
"编译"到:
var o;
o = {
a: 1,
b: 2,
c: 3
};
with(o) {//;
alert(a);
};
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这是Doug Crockford的观点被视为福音的另一个领域.with语句被认为有害是基于属性写入的模糊性拒绝它,但是当与只读上下文对象一起使用时忽略它的用处,例如定义类似DSL的API的上下文对象.
CoffeeScript的Coco fork支持with语法; 请参阅https://github.com/satyr/coco/wiki/additions.但是,该语法只是设置this块中目标对象的值,而不是编译为有问题和已弃用的with关键字.
假设你想with在CoffeeScript中模仿Coco的语法.你会做这样的事情:
withObj = (obj, func) -> func.call obj
Run Code Online (Sandbox Code Playgroud)
然后你可以写
withObj = (obj, func) -> func.call obj
withObj annoyingly.lengthy.obj.reference, ->
@foo = 'bar'
@bar = 'baz'
Run Code Online (Sandbox Code Playgroud)
当然,在这种简单的情况下,最好使用像jQuery或Underscore这样的实用程序函数extend:
_.extend annoyingly.lengthy.obj.reference, foo: 'bar', bar: 'baz'
Run Code Online (Sandbox Code Playgroud)