创造一个功能是存储在哈希JS对象时,“这个'所覆盖到窗口对象 [英] 'this' being scoped to window object when creating JS object where function is stored in a hash
问题描述
我不知道,如果标题这使得任何意义,但本质上我试图写一个应用程序我工作在一个非常简单的JavaScript依赖注入容器。
I'm not sure if the title to this makes any sense, but essentially I am trying to write a very simple Javascript dependency injection container for an app I am working on.
这是容器:
jedi = new function() {
var library = {};
this.module = function(name, module) {
if (arguments.length == 1) {
return library[name];
}
library[name] = module;
};
};
我然后创建一个骨干模型并将其添加为像这样的依赖关系:
I then create a Backbone model and add it as a dependency like so:
(function () {
var addColourSchemeModel = Backbone.Model.extend({
getColourJSON: function(prop) {
var cols = this.get(prop).split(',');
return {
R: cols[0],
G: cols[1],
B: cols[2]
};
}
});
jedi.module('AddColourSchemeModel', addColourSchemeModel);
})();
当我尝试创建这个模块,像这样的一个新的实例会出现问题:
The problem occurs when I try to create a new instance of this module like so:
var colourModel = new jedi.module('AddColourSchemeModel')({
// json object containing model values
});
我得到一个错误对象[对象全球]没有办法设定
。
但奇怪的是骨干示范初始化方法等被调用,但这个
被所覆盖的窗口,而不是对象被初始化,这就是错误被ocurring因为它试图调用 this.set
在某些时候,但其实这是窗口。
The strange thing is the Backbone Model initialize methods etc are being called, but this
is being scoped to the window instead of the object being initialized, this is where the error is ocurring as it is trying to call this.set
at some point but this is actually the window.
推荐答案
这是所有的,因为如何在执行时都没有的JavaScript的为本,上下文结合。它会导致来自不同背景的人最初的混乱。 失控用JavaScript绑定情况你所看到的提供了极好的解释。有各种技术来解决这样的: - )
This is all because of how javascript does the binding for 'this', the context when executing a all. It causes initial confusion for people from other different background. Getting Out of Binding Situations in JavaScript provided excellent explanation on what you are seeing. There are various techniques to address this :-)
下面是一些文章,可能会有帮助,
Here are a few articles that may help,
- 走出绑定的情况在JavaScript中
- 了解绑定和bindAll骨干.js文件
- 是VAR自我=这一点;错误的思路?
- what-is-the-difference-between-this-self-window-and-window-self
- Getting Out of Binding Situations in JavaScript
- Understanding Bind and bindAll in Backbone.js
- Is var self = this; a bad pattern?
- what-is-the-difference-between-this-self-window-and-window-self
希望这有助于。
这篇关于创造一个功能是存储在哈希JS对象时,“这个'所覆盖到窗口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!