简单构造函数模式

simple Constructor Pattern

本文关键字:模式 构造函数 简单      更新时间:2023-09-26

我以前使用过oop风格的脚本,并试图获得某种带有javascript的系统。我想尝试最基本的模式,构造函数模式。

因此,我设置了一个名为ImageView的js文件,该文件的构造函数与js文件的名称相匹配。

    function ImageView(){
    alert( 'this is working');
}

然后我设置了另一个名为Main.js的js文件,它将成为主要的实例化类。

    $(document).ready(function(){
    var imageViewer = new ImageView();
    //ImageView();
});

现在我没有得到的是,我可以调用这个对象ImageView,甚至不需要新的构造函数调用。例如ImageView()。据我所知,这只是另一个全局函数,而不是一个封装类。我正试图摆脱全局垃圾,将我的方法和属性分离到它们自己的类中。我想念她是什么。

其他人已经回答了使用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引入的聪明的全局变量是函数definerequire,但如果你正确使用它们,你可以避免在这两个函数之外再引入任何全局变量。

ImageView内部,如果用new调用this,则其值将不同。没有,它只是另一个功能。使用new,它将创建一个新的ImageView实例并将其绑定到变量this

首先,JavaScript没有内置的名称空间。它只能被模拟。您还必须包含计划使用的每个javascript文件。

只调用ImageView(),基本上调用this上的构造函数,这是下一级作用域。

使用new ImageView()创建构造函数ImageView的新Object,this指向新实例。

JavaScript是一种类型松散的原型语言。