JavaScript "Static Object"或库

标签 javascript object

我不确定我是否使用了正确的术语,因为我是面向对象编程的新手。我可以通过以下方式制作“传统元素”:

(新文件:Person.js)

function Person() {
    this.name;
    this.getName = function getName(){
        return this.name;
    }    
    this.setName = function setName(name){
        this.name = name;
    }
}

然后要在主文件中使用它,我必须输入:

var myFriend = new Person();
myFriend.setName("Bob");

为了使用它。您必须创建对象的实例才能使用其功能。

我想创建的是我认为至少在 Java 中或可能是一个库中称为“静态对象”的东西。我正在考虑类似于使用内置数学函数的方法。我会打字

Math.sin(3.14);

无需执行以下操作:

var myMath = new Math();
myMath.sin(3.14);

有效,我想要一个图书馆,但我不知道如何设置

(文件:mathlib.js)

//mathlib.js
function mathlib() {
    this.printStuff = function printStuff(){
        alert("mathlib print");
    }
}

然后在主文件中:

mathlib.printStuff();

这给出了一个错误:TypeError: mathlib.printStuff is not a function

不确定我哪里出错了..(我以与以前相同的方式包含文件)

最佳答案

您正在寻找的是 javascript 中的模块模式。它相当于 Java 中实用程序类的 js。在 javascript 中看起来像这样。

实用程序.js

var Utilities = (function(){
    return {  

        addTwoNumbers : function(num1, num2){
            return num1 + num2;
        },

        greatestCommonFactor : function(num1, num2){
            while(num1 != num2){
                if(num1 > num2)
                    num1 -= num2;
                else
                    num2 -= num1;
            }
            return num1;
        }
    }
}());

然后您可以在代码的其他地方执行以下操作:

var sum = Utilities.addTwoNumbers(11, 17);
var gcf = Utilities.greatestCommonFactor(21, 35);

您只需确保将文件包含在 html 中,通常在使用它的脚本之前。

<script src="js/Utilities.js"></script>
<script src="js/main.js"></script>

有很多方法可以扩展模块和/或使代码更具可读性。只需搜索“javascript module pattern”,但上面的代码应该能让您有个好的开始。

关于JavaScript "Static Object"或库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32508099/

相关文章:

javascript - 带有 chop 文本和元素的行坚持在右边

javascript - 获取占据父元素顶部的元素

javascript - 检查 HTML5 视频的文件大小

javascript - 使用 d3.js 绑定(bind)数据内的数组(动态生成恒定的 d3.svg.line)

javascript - Material -ui选择器: how to hide text field and open modal with button

javascript - $scope 和 $rootScope 的区别

javascript - 从包含特定字符串作为 Javascript 子字符串的对象中选取键

java - 无法返回对象类型?

javascript - 在 Object.create 中使用对象文字与函数表达式之间有区别吗?

c++ - 函数如何读取指针?