大家好,我一直在从Mark Bates Programming in coffeescript pdf这本书中学习咖啡脚本,尽管两者似乎都有相同的实现,但我一直对 javascript 的行为大发雷霆
示例-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()
对应的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();
这会提醒“你的代码被黑了!”
示例 2
class Emp
constructor: (@attributes)->
printInfo: ->
alert "Name: #{@attributes.name}"
emp2 = new Emp
name: "Mark"
printInfo: ->
alert "Hacked ur code"
emp2.printInfo()
对应的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();
这会提醒“姓名:马克”
区别在哪里?