我以前使用过oop风格的脚本,并试图用javascript实现某种系统。我想尝试最基本的模式,构造器模式。
因此,我设置了一个名为ImageView的js文件,其构造函数与该js文件的名称相匹配。
function ImageView(){
alert( 'this is working');
}
然后,我设置了另一个名为Main.js的js文件,它将成为主要的实例化类。
$(document).ready(function(){
var imageViewer = new ImageView();
//ImageView();
});
现在我不明白的是,我可以在不调用新构造函数的情况下调用这个对象ImageView。例如ImageView()。据我所知,这只是另一个全局函数,而不是封装的类。我试着从全局的废话中解脱出来,将我的方法和属性分离到它们自己的类。我还想她什么呢。
发布于 2011-06-28 11:23:21
其他人已经回答了使用new
和不使用它之间的区别,所以我将回答您完全独立的问题:如何在JS中避免全局变量?
答案是,你不能完全。您将始终至少有一个,您可以在其中填充您的其他东西。例如,如果你想要一个xyz
的“名称空间”,你可以这样做:
// global:
var xyz = {}; // or, window.xyz = {} if you are in a browser and want to be more explicit.
// "encapsulated" within the xyz "namespace":
xyz.ImageView = function () { alert("This is working"); };
有一个更好的解决方案:使用新兴的JavaScript模块概念。这些不是语言特性(至少在当前版本的JavaScript中不是),所以它们实际上只是非常聪明的库引入的一些技巧,它们覆盖了几个全局变量,使您可以避免创建比这些库提供的变量更多的全局变量。RequireJS就是一个很好的例子,您可以执行以下操作:
// In xyz.js, define the xyz module (name automatically derived from filename).
// Whatever is returned from the function you pass to define is "the xyz module"
define(function () {
return {
ImageView: function () { alert("This is working"); }
};
});
// In other code, in a different file, you can say "I require the xyz module
// to do my work," and pass require a function saying "once you've got the xyz module
// for me, here's the work I will do with it".
require(["xyz"], function (xyz) { // dependency array maps to callback arguments
// I got the xyz module, including the ImageView function it exported. Use it!
var imageViewer = new xyz.ImageView();
});
在这里,RequireJS引入的聪明的全局变量是函数define
和require
,但是如果使用得当,您可以避免在这两个函数之外引入更多的全局变量。
发布于 2011-06-28 11:02:22
首先,JavaScript没有内置的命名空间。它只能被模拟。您还必须包括您计划使用的每个javascript文件。
你说的对,调用ImageView()
基本上就是调用this
上的构造函数,这是下一层的作用域。
使用new ImageView()
创建构造函数ImageView的新对象,并且this
指向新实例。
JavaScript是一种松散类型的原型语言。
发布于 2011-06-28 11:03:18
在ImageView
内部,如果用new
调用this
,它的值将会有所不同。如果没有,它只是另一个函数。使用new
,它将创建一个新的ImageView
实例并将其绑定到变量this
。
https://stackoverflow.com/questions/6501066
复制相似问题