我在JS文件中有以下对象:
var IOBreadcrumb = function IOBreadcrumb() {
this.breadcrumbs = [];
this.add = function(title, url) {
var crumb = {
title: title,
url:url
};
this.breadcrumbs.push(crumb);
};
};
Run Code Online (Sandbox Code Playgroud)
在另一个JS文件中我想利用这个对象:
//this occurs in some on click event
var breadcrumb = new IOBreadcrumb();
breadcrumb.add('some title',url);
console.log(breadcrumb.breadcrumbs);
Run Code Online (Sandbox Code Playgroud)
我希望只有1个IOBreadcrumb实例,所以当我点击一个按钮时,它总是会向数组中添加一个breadcrumb.
我怎么能做到这一点?
var IOBreadcrumb = {
breadcrumbs: [],
add: function(title, url) {
var crumb = {
title: title,
url:url
};
IOBreadcrumb.breadcrumbs.push(crumb);
}
};
Run Code Online (Sandbox Code Playgroud)
然后:
IOBreadcrumb.add('some title',url);
console.log(IOBreadcrumb.breadcrumbs);
Run Code Online (Sandbox Code Playgroud)
制作类似以下内容的第一个由您的页面执行的javascript.
(function(){
var setup = function IOBreadcrumb() {
this.breadcrumbs = [];
this.add = function(title, url) {
console.log('adding');
var crumb = {
title: title,
url:url
};
this.breadcrumbs.push(crumb);
}
};
window.IOBreadcrumb = new setup();
})(window);
Run Code Online (Sandbox Code Playgroud)
这是初始设置.现在你可以在任何地方做
IOBreadcrumb.add()
我在http://jsfiddle.net/xmHh5/测试了这个
这样做是window.IOBreadcrumb为了分配立即执行的函数的结果.由于此函数没有句柄,因此无法重新执行它.因为你正在放置IOBreadcrumb窗口对象,它实际上是全局的.我假设这是在浏览器中运行; 它不会在node.js或任何东西上运行,因为它依赖于它window.