使用CoffeeScript扩展Javascript对象 [英] Extending Javascript objects with CoffeeScript
问题描述
我想通过向原型中添加一个方法来添加扩展JavaScript对象的能力。
该方法将接收一个或多个其他对象,并将所有键/值添加到 this
。
这是我想出的:
I want to add the ability to extend javascript objects by adding a method to the prototype.
The method will receive one or more other objects and will add all of the key/values to this
.
This is what I came up with:
Object::extend = (objects...) ->
@[key] = value for key, value of object for object in objects
this:
Object::extend = (objects...) ->
for object in objects
for key, value of object
@[key] = value
两者都按预期工作,并编译成相同的JavaScript代码:
Both work as expected, and compile into the same javascript code:
var __slice = [].slice;
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len, _results;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
_results = [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
_results.push((function() {
var _results1;
_results1 = [];
for (key in object) {
value = object[key];
_results1.push(this[key] = value);
}
return _results1;
}).call(this));
}
return _results;
};
我不太高兴是每个for循环创建的整个结果\\ b
$ b
What I'm not too happy about is the whole results thing that is created per for loop which is completely redundant for my purpose.
Is there a way to get a code more like:
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
(function() {
for (key in object) {
value = object[key];
this[key] = value;
}
}).call(this);
}
};
感谢。
I'm aware that I can simply embed javascript code, but looking for a coffeescript solution.
推荐答案
您可以尝试添加一个显式的 return
:
You can try adding an explicit return
:
Object::extend = (objects...) ->
for object in objects
for key, value of object
@[key] = value
return
产生这个:
var __slice = [].slice;
Object.prototype.extend = function() {
var key, object, objects, value, _i, _len;
objects = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
for (key in object) {
value = object[key];
this[key] = value;
}
}
};
每个CoffeeScript函数都返回函数中最后一个表达式的值,CoffeeScript循环也是表达式。这意味着CoffeeScript必须构建所有 _results
的东西来为你的函数产生一个返回值,因为你有一个隐式的 return
应用于外环。如果通过添加一个显式的return nothing删除隐式的 return
,那么CS&rss; JS编译器似乎足够聪明,不能做所有的额外的 _results
工作。
Every CoffeeScript function returns the value of the last expression in the function, CoffeeScript loops are also expressions. That means that CoffeeScript has to build all that _results
stuff to produce a return value for your function since you had an implicit return
applying to the outer loop. If you remove that implicit return
by adding an explicit "return nothing" then the CS→JS compiler seems to be smart enough to not do all that extra _results
work.
这篇关于使用CoffeeScript扩展Javascript对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!