Hi all I have been learning coffeescript from the book Mark Bates programming in coffeescript pdf I have been banging my head off at the behavior of javascript even though both seems to have same implementation
Example-1
class Employee
constructor: (@attributes)->
for key, value of @attributes
@[key] = value
printInfo: ->
alert "Name: #{@name}"
emp1 = new Employee
name: "Mark"
printInfo: ->
alert "Hacked ur code !"
emp1.printInfo()
Corresponding javascript
var Emp, Employee, emp1, emp2;
Employee = (function() {
function Employee(attributes) {
var key, value, _ref;
this.attributes = attributes;
_ref = this.attributes;
for (key in _ref) {
value = _ref[key];
this[key] = value;
}
}
Employee.prototype.printInfo = function() {
return alert("Name: " + this.name);
};
return Employee;
})();
emp1 = new Employee({
name: "Mark",
printInfo: function() {
return alert("Hacked ur code !");
}
});
emp1.printInfo();
This alerts "Hacked ur code !"
Example-2
class Emp
constructor: (@attributes)->
printInfo: ->
alert "Name: #{@attributes.name}"
emp2 = new Emp
name: "Mark"
printInfo: ->
alert "Hacked ur code"
emp2.printInfo()
Corresponding javascript
Emp = (function() {
function Emp(attributes) {
this.attributes = attributes;
}
Emp.prototype.printInfo = function() {
return alert("Name: " + this.attributes.name);
};
return Emp;
})();
emp2 = new Emp({
name: "Mark",
printInfo: function() {
return alert("Hacked ur code");
}
});
emp2.printInfo();
This alerts "Name: Mark"
Where is the difference ?
In the first example, all properties of the object you pass to the constructor (
attributes) are added to the current instance (that’s what the loop does). Instance properties hide prototype properties, that’s why theprintInfofunction you passed to the constructor is executed. You can access the original method by usingEmployee.prototype.printInfo.call(emp1);In the second example, nothing like this happens. The
attributesobject just lives inside theattributesproperty of the instance. To get a different alert, you need to writeemp2.attributes.printInfo();