Given:
var table = new Array(10);
what means in java script this new
?
When I write:
var table = Array(10)
it gives me the same result.
Given:
var table = new Array(10);
what means in java script this new
?
When I write:
var table = Array(10)
it gives me the same result.
new
will change the context of a function to a blank object that will then be returned to the calling code.
function noNewTest(){
// this === window/execution context
}
function newTest(){
// this === {}
}
var test;
test = new newTest(); // test === newTest object instance even though we didn't return anything from the newTest function
test = noNewTest(); // test === undefined because we didn't use new and didn't return anything from noNewTest
Also note, that whatever you return from a constructor function will override what new
returns.
Oh, that duplicate explains it in more depth than I did. Go look at hat.
The 'new' keyword is used to create a new instance of a js entity. For example: var tableOne = [1,2,3]; var tableTwo = new Array(1,2,3);
will yield the same results but tableOne is simply assigning an array of three numbers to the tableOne namespace whereas tableTwo is creating a brand new array using new Array() and assigning the same value to the tableTwo namespace. The new keyword is often used in prototypes to create a new instance of an object with a class.