undefinedfix
Sign in

Both foo() and new foo() in JS can execute corresponding methods. What's the difference?

jsibs edited in Wed, 30 Dec 2020
function fun(){
alert(111)
}
fun()
var aaa=new fun()

As shown in the above code, if I want to alert (111), I can use fun() or new fun() to call it. Since the two calling methods are the same, what are the advantages of using the new keyword to call them?

3 Replies
John
commented on Wed, 30 Dec 2020
var cl=console.log;
var a=fun();
var b=fun();
var c=new fun();
cl(a===b);//true
cl(a===c);//false
cl(a instanceof fun);//false
cl(c instanceof fun);//true
cl(fun instanceof Function);//true
aateeque
commented on Wed, 30 Dec 2020

I changed your code:

var val = 111;
function fun(){
alert(this.val)
}
fun()
var aaa=new fun()

If you understand the reason, you will understand.

suxbr
commented on Wed, 30 Dec 2020

You'd better first understand what new is used for. For alert (111), you use new to do a simple static page. You have to use framework, webpack, ES6 and sass to do it. Then you ask why you use so many things to do what jQuery can do

lock This question has been locked and the reply function has been disabled.