开发者

new operator means in JQuery

I came across this code in Internet. It is about a plugin that implements printing functionality. I am just wondering what does the new operator means while invoking the function.

$.fn.printArea = function( options )
{
  printWindow = new Popup();
  writeDoc = printWindow.doc;
}

function Popup()
{
    var windowAttr = "location=yes,statusbar=no,directories=no,menubar=no,titlebar=no,toolbar开发者_运维知识库=no,dependent=no";
    windowAttr += ",width=" + settings.popWd + ",height=" + settings.popHt;
    windowAttr += ",resizable=yes,screenX=" + settings.popX + ",screenY=" + settings.popY + ",personalbar=no,scrollbars=no";

    var newWin = window.open( "", "_blank",  windowAttr );

    newWin.doc = newWin.document;

    return newWin;
}

If someone could explain the rational behind calling the popup function in new, I would really appreciate it.


printWindow = new Popup();
// is the same as
// create a new `this` scope for the Popup function from the prototype.
var temp_this = Object.create(Popup.prototype);
// call the function with the `this` context and store the result.
var o = Popup.call(temp_this);
// if the result is an object then assign it to the variable
// otherwise assign the `this` value to the variable.
printWindow = typeof o === "object" ? o : temp_this;
// It actually does more. Go read the ES5 spec.

In this case Popup is a silly constructor that returns an object anyway so the new keyword is useless because this is not returned internally.

It's simply valid but useless code for this Popup function.


The new operator creates a new object of Popup(). This way, if you would have multiple different popups, you could create them by saying:

popup1 = new Popup();
popup2 = new Popup();

And then you would be able to give them their own parameters.

EDIT thanks to pst in the comments

This is not the situation here, however. Note that the "constructor" returns -- thus the "new object" is silently discarded and the object contained in newWin is returned.


A new instance of Popup (class) is instantiated and assigned to the variable printWindow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜