假设有一个简单的对象文字,其名称永远不会改变:
var car = {
wheels : 4,
construct : function() {
var that = this;
setTimeout(function() {
console.log(that.wheels);
console.log(car.wheels);
}, 500);
}
};
我的问题是:哪种方式更好?通过对象名称引用或创建新变量(这可能需要一些时间和内存,并且可能必须在多个函数中完成)?
最佳答案
在对象内,您应该始终通过 this
(或其副本,例如 that
,如果需要)引用该对象,以防止以下损坏:
var car = ...
// do stuff
car = undefined; // or anything else, perhaps by a code hacker in the JS console
// class is now broken
您应该将外部赋予对象的变量名称视为您未知的变量名称,并且可能会发生更改。
其他人可能会称其为其他名称,可能有多个名称,该名称可能突然完全指向某个其他对象。这些变量是为了对象引用的“所有者”的利益,而不是为了对象本身。
关于javascript - 简单对象文字的最佳实践 : using "that" or the object's name?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18921388/