you don't use
newwhen defining the function, but rather you usenewwhen you call the function with the intent to make a new object.if you use
newwhen 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.