“new” operator before declaring function

后端 未结 2 1607
面向向阳花
面向向阳花 2021-01-25 09:38

Like explore javascript as my first reference to the whole programming but as i\'m not the professional can\'t comprehend a lot of stuff. So it would be so much appreciated if

相关标签:
2条回答
  • 2021-01-25 09:42

    Those are completely different things. The second one is a standard javascript function declaration (and can be called with sayHi();), while the first should be rewritten as

    new (function sayHi() { alert('hi'); });
    

    Now you can see it is a (named) function expression, which is directly passed to the new operator. This should not be used, if you really wanted to call it immediately (there are applications) use (function(){…})());.

    0 讨论(0)
  • 1) you don't use new when defining the function, but rather you use new when you call the function with the intent to make a new object.

    2) if you use new when you're defining the function, it means that it will fire right away. This can be handy sometimes... ...but it's really not how a beginner should learn. Also, the more-accepted version of this technique is called an IIFE (Immediately Invoked Function Expression), which looks like

    (function () {
    /* function stuff in here */
    }());
    

    instead of

    new function () { /* function stuff in here */ }
    

    If you try to define a function that way, you will get an error if you try to use it, later (because it's not defined).

    Here are two ways of actually defining functions:

    var sayHi = function () { console.log("Hi!"); };
    

    and

    function sayHello () { console.log("Hello"); }
    

    Neither of these use new.

    In order to call them, and have them do their job, you don't need to use .call(). .call() will work, but it has a special purpose which you won't need for a very long time.

    All you need to do is this:

    sayHello();
    sayHi();
    

    New is intended to be used when you want to make a certain kind of object.

    Making objects in JavaScript is very simple:

    var obj = {};
    var person = { name : "Bob" };
    
    person.name; // "Bob"
    person.age = 32;
    

    Working with objects is very, very easy.

    But in other programming languages, you need classes which are like blueprints for an object.

    In JS, you might make a class like this:

    function Person (name, age) { this.name = name; this.age = age; }
    

    and then use it like:

    var bob = new Person("Bob", 32);
    bob.name; // "Bob";
    bob.age;  // 32;
    

    See where I put the new?
    I used a function which makes people, and I said that I want bob to be a new Person.

    But again, in JS, this can be as easy as:

    var mike = { name : "Mike", age : 20 };
    

    Didn't have to build a function, didn't have to use new. It just worked.

    0 讨论(0)
提交回复
热议问题