Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Window.prototype.confirm and Window.confirm

Tags:

javascript

What is the difference between Window.prototype.confirm and Window.confirm?

I am working on a change request which says We need to have a title on confirm message box . I was just going through the code which pops up this confirm window.

In a javascript there is a call to

Window.prototype.confirm = function(arg){return false;}; 

which is responsible to pop up the confirm window

I searched in google there is a javascript function like window.confirm where we cant set title and we need to write some custom javascript function to do the same

So I am just wodering whether Window.prototype.confirm and Window.confirm are same and if not what is the difference?

like image 820
Programmer Avatar asked Mar 22 '26 23:03

Programmer


2 Answers

You haven't seen Window.confirm, it was window.confirm.

Type the following lines into the Chrome JavaScript console, one by one, and it may help shed some light on this. (Type the part after the > and it will print what you see below that.)

> window.constructor
  function Window() { [native code] }
> window.constructor === Window
  true
> window.confirm === Window.prototype.confirm
  true
> window.confirm = function() { alert('oops'); };
  function () { alert('oops'); }
> window.confirm === Window.prototype.confirm
  false
like image 188
Michael Geary Avatar answered Mar 25 '26 11:03

Michael Geary


It has to do with JavaScripts native inheritance model.

  1. You access the confirm method of the prototype of Window.

    Window.prototype.confirm

  2. You access the confirm method of an instance of Window named window.

    window.confirm (notice lowercase w)

As you can see window is an instance of Window meaning that if you change window.confirm you have only changed it for this specific instance. Other instances of Window will have the original function. If however you change the confirm function of the prototype of Window then all instances of window will use the new implementation.

Using a custom object to illustrate.

function MyObject () {

}

MyObject.prototype.test = function () {
     alert('A');
}

var myobj1 = new MyObject();
var myobj2 = new MyObject();

myobj1.test(); // alerts A
myobj2.test(); // alerts A

myobj1.test = function () { alert('B'); };

myobj1.test(); // alerts B
myobj2.test(); // alerts A

MyObject.prototype.test = function () { alert('C'); };

myobj1.test(); // alerts C
myobj2.test(); // alerts C
like image 30
Jacob T. Nielsen Avatar answered Mar 25 '26 13:03

Jacob T. Nielsen