创建自定义 Javascript 对象的惯用方法有哪些

What are some idiomatic ways to create custom Javascript objects

本文关键字:方法 自定义 Javascript 对象 创建      更新时间:2023-09-26

我正在创建一个自定义对象,以便在我工作的一些内部应用程序中使用。我研究了一些方法来做到这一点 - 这就是我得出的。

function ISGrader(text)
{
this.text = text;
this.printInfo = function(){
    alert("Object working " + text);    
}
this.putGrade = function(score)
{
           alert(score);
}
 }

我相信这显示了构造函数类型的功能,以及我将基于其构建的一些简单的入门方法。

是上述良好做法还是有其他更标准的方法?

我更喜欢类似于下面的模式。您可以将其视为 4 步方法:

(function(parent) {
// 1. Declare private variables and functions that will be
// accessible by everybody within the scope of this 
// function, but not outside of it.
var doSomethingAwesome = function() { .. }; // private function
var coolInteger = 42; // private variable
// 2. Create the constructor function
function ISGrader() {
    ..
}
// 3. Create shared public methods on the prototype object.
// These will be created only once, and shared between all objects
// which is more efficient that re-creating each method for each object.
ISGrader.prototype.printInfo = function() { .. };
ISGrader.prototype.putGrade = function(score) { .. };
// 4. Expose the constructor to the outside world.
parent.ISGrader = ISGrader;
})(window);

所有内容都包含在自执行匿名函数中的原因是为了确保我们在内部创建的私有变量不会泄漏到封闭范围之外,并且基本上保持清洁。

像这样声明构造函数的另一个好处是,您可以通过更改单个单词轻松地将父对象从 window 更改为另一个命名空间对象。

我更喜欢这种模式(IIFE),但这纯粹是意见:

var ISGrader = (function (text) {
    // anything declared here is "private"
    var printInfo = function() {
        alert("Object working " + text);    
    };
    var putGrade = function (score) {
        alert(score);
    };
    // put "publicly" accesible things in the returned object
    return {
        text: text,
        printInfo: printInfo,
        putGrade: putGrade
    };
})(text);

始终建议使用"原型"来执行此操作。这样,您还可以继承其属性并创建新属性。

var ISGrader = function(text) {
    this.text = text;
    var _privateVar = text;
    this.updatePrivateVar = function(newText) {
        _privateVar = newText;
        alert("private variable updated");
    }
}
ISGrader.prototype.text = "";
ISGrader.prototype.printInfo = function() {
    alert("Object working " + this.text);
}
ISGrader.prototype.putGrade = function(score) {
    alert(score);
}
var isGrader = new ISGrader("hello");
isGrader.printInfo();

// Inherit and create a new definition
var ISGrader2 = function() {}
ISGrader2.prototype = new ISGrader();
var isGrader2 = new ISGrader("hello2");
isGrader2.printInfo();
isGrader2.updatePrivateVar("hello3");

演示 : http://jsfiddle.net/rkspP/3/

虽然不是真正的答案,但我推荐 Douglas Crockford 的书 JavaScript: The Good Parts,因为它很好地向您介绍了该语言的"优点",并讨论了在 JavaScript 中创建对象的不同方法的优缺点。

如果您只是在寻找 JavaScript 对象中成员可见性的说明,也可以查看此资源: http://javascript.crockford.com/private.html

如果您计划在单个页面上创建多个ISGrader对象,则将函数粘贴到分配给ISGrader的原型对象中会更节省内存,如下所示:

function ISGrader(text) {
    this.text = text;
}
ISGrader.prototype = {
    printInfo: function() {
        alert("Object working " + this.text);
    },
    putGrade: function(score) {
        alert(score);
    }
}