Стр. 65,
var myapp = {};
myapp.color = "green";
myapp.paint = function (node) {
node.style.color = this.color;
};
//...
var findNodes = function (callback) {
// ...
if (typeof callback === "function") {
callback(found);
}
// ...
};
Цитата:
|
If you call findNodes(myapp.paint), it won’t work as expected, because this.color will
not be defined. The object this will refer to the global object, because findNodes() is a
global function. If findNodes() were a method of an object called dom (like
dom.findNodes()), then this inside of the callback would refer to dom instead of the
expected myapp.
|
Это я чего-то не догоняю, или в книге ошибка?
var myapp = {};
myapp.color = "green";
myapp.paint = function (node) {
alert(this);
};
//...
var obj = {
property : 1,
findNodes: function (callback) {
if (typeof callback === "function") {
callback();
}
}
};
obj.findNodes(myapp.paint)
this, как и положено, внутри callback указывает на window, т.к. контекст не указан. Но автор книги обещает нам привязку callback'а к текущему контексту.