gpt4 book ai didi

javascript - 在这个例子中,我的对象方法是如何被破解的?

转载 作者:行者123 更新时间:2023-11-30 13:14:29 25 4
gpt4 key购买 nike

<分区>

大家好,我一直在学习 Mark Ba​​tes programming in coffeescript pdf 一书中的 coffeescript,尽管两者似乎具有相同的实现,但我一直在努力研究 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();
 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()

对应的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"

区别在哪里?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com