"伪造“;JavaScript构造函数

"Faking" a JavaScript Constructor

本文关键字:JavaScript 构造函数 伪造 quot      更新时间:2023-09-26

上下文

我正在努力提高我的JavaScript技能,我正在学习更多关于原型的知识。我想更好地理解这个问题中的代码以及它的任何限制或问题。

有一件事并不明显,那就是定义更复杂的构造函数,这些构造函数所做的不仅仅是简单的初始化。我想做的是让一个类在创建web服务时调用它,而不需要在初始化后立即调用方法。

我所做的是创建一个属性,并为其分配一个自调用的匿名方法。它看起来像我希望的那样工作,但我不知道是否有更好的方法。

代码

function AsyncOrderLine(productID) {
    var context = this;
    this.autoValue;
    this._productID = productID;
    this._asyncRequestComplete = false;

    this.hello = function () {
        alert("hello world");
    }
    this.constructor = (function () {
        context.hello();
        context.autoValue = "testing: " + productID + "(" +        context._asyncRequestComplete + ")";
    })()

}

结果

 var _asyncOrderLine = new AsyncOrderLine(1001);

显示警报:"Hello World">

 _asyncOrderLine.autoValue = testing: 1001(false)
 _asyncOrderLine.constructor = 'undefined'

在这种情况下,我希望构造函数在创建对象后保持未定义状态。

问题

有更好的方法吗?使用这种方法会有任何不可预见的副作用吗?

没有必要让事情复杂化。您可以在构造函数中运行任何您想要的代码:

function AsyncOrderLine(productID) {
    this.autoValue;
    this._productID = productID;
    this._asyncRequestComplete = false;
    this.hello = function () {
        alert("hello world");
    }
    // Run whatever arbitrary code you want...    
    this.hello();
    this.autoValue = "testing: " + productID + "(" + context._asyncRequestComplete + ")";
}

正如其他人所说,构造函数属性没有任何理由。你可以在函数体中运行你想要的任何代码,它将在对象初始化时运行。如果你想运行异步代码(比如ajax调用(,那么你可能想把一个完成函数传递到构造函数中,这样对象的创建者就可以知道对象初始化的异步部分何时真正完成,因为当对象从初始化返回时,它不会完成。看起来像这样:

function function AsyncOrderLine(productID, fn) {
    // initialization code for the object here
    this._asyncRequestComplete = false;
    ...
    // kick of asychronous networking call here
    var context = this;
    $.getJSON(url, function(data) {
        // process the data response into our object here
        context.whatever = data;
        context._asyncRequestComplete = true;
        // call the completion function with `this` set to point to our object here 
        // so the creator of this object can know when the async part of
        // initialization is actually done
        fn.call(context);
    });
}

然后,打电话的人会做这样的事情:

var x = new AsyncOrderLine(id, function() {
    // can reference new object and it's methods and properties via "this"
    alert("orderLine object is now completely initialized");
});