node.js - binding values while looping in constructor CoffeeScript -
i have decided use coffeescript , have been trying convert node.js module of mine coffeescript. so, here code in js:
function domain(obj){ var self = this; (var key in obj){ this[key] = obj[key]; //merge values } } domain.prototype.save = function(fn){ } and attempt have same in coffeescript following:
class domain consructor: (obj) -> own key, value of obj @key = value save: (fn) -> module.exports = domain the following test fails:
require('coffee-script'); var should = require('should') , domain = require('../index'); should.exist(domain); var domain = new domain({'attone':1, 'atttwo':2}); domain.should.have.property('save'); domain.should.have.property('attone'); domain.should.have.property('atttwo'); domain.save.should.be.an.instanceof(function); console.log('all tests passed'); the property 'attrone' , 'attrtwo' not binding domain class. have compiled coffee code 'coffee -c index.coffee' see js code:
(function() { var domain, __hasprop = {}.hasownproperty; domain = (function() { function domain() {} domain.prototype.consructor = function(obj) { var key, value, _results; _results = []; (key in obj) { if (!__hasprop.call(obj, key)) continue; value = obj[key]; _results.push(this.key = value); } return _results; }; domain.prototype.save = function(fn) {}; return domain; })(); module.exports = domain; }).call(this); from compiled js, see '_result' array being generated , returned never binded 'this'. how bind array class scope pass test?thank you
your line of coffeescript
@key = value is not equivalent javascript want
this[key] = obj[key]; the way @ works is replaced either this or this.. thus, @key compiles this.key. should instead use
@[key] = value additionally, spelled constructor wrong (as consructor). in coffeescript, constructor special method compiles differently normal method; if spelled wrong, coffeescript assumes want empty one.
Comments
Post a Comment