I was trying the below commands on Chrome console. I am able to create the object using new(line 2 below) but using call doesn't work. Can anyone explain what could be the reason ?
function ObjConstructor(){ this.sample = 1};
let withNew = new ObjConstructor();
let usingCall = ObjConstructor.call({});
usingCall
undefined //output that came on console, this is not a command
withNew
ObjConstructor {sample: 1} //output that came on console
new does several things including:
Creating an object
Setting the this value to that object
Causes the function to return that object by default
Your code:
Creates an object manually with {}
Sets the this value to that object with call()
… but doesn't do the last thing. There is no return statement in the function, so it returns undefined.
The result of call is whatever the function returns. Your ObjConstructor doesn't return anything, so the result of calling it is undefined.
In contrast, when you use new, a new object is created and passed to the function, and unless the function returns a non-null object, the object created for new is the result of the new expression.
That's why the new version works but the call doesn't.
Also note that call doesn't create an object at all. In your ObjConstructor.call({}), what creates the object is {}, not call. It won't have ObjConstructor.prototype as its prototype. ({} is a raw object initializer, so the object will have Object.prototype as its prototype.)
try this.
Or look at this -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
var MyType = function(_param1,_param2){
this.param1 = _param1;
this.param2 = _param2;
this.ShowParam = function(){
alert(this.param1+" - "+this.param2);
}
}
var test = new MyType("PARAM TEST 1","PARAM TEST 2");
alert(test.param1+" - "+test.param2);
var test2 = new MyType("PARAM TEST 1.2","PARAM TEST 2.2");
alert(test2.param1+" - "+test2.param2);
test.ShowParam();
test2.ShowParam();
Related
Object A has an array of instances of Object B.
Object A also has a getter method that takes in an index and returns the relevant Object B.
Object B has a set of methods that can be called.
I'm trying to call the object B method using an object chain ( a.getB().method() )like below:
class ObjectB{
foo(){return 'bar'}
}
class ObjectA{
constructor(){
this.list = []
}
addB(){this.list.push(new ObjectB)}
getB(index) { if(index < this.list.length) return this.list[index]}
}
a = new ObjectA();
a.addB();
a.getB(0).foo(); // Works
a.getB(4).foo(); // Returns error, since getB(4) is undefined and has no foo()
I tried different else statements in getB() but I can't stop the script from trying to access 'output'.foo().
I tried a try catch in getB(), but I can't force it to give an error at getB(4). Is there a clean way from me to handle this potential issue without try/catching every instance of the last line?
Use the optional chaining operator:
a.getB(4)?.foo()
You can also add it for function calls:
a.getB(4)?.foo?.(). This last solution works if getB(4) returns an object that is defined, but has no foo function.
Consider the following snippet :-
function Custom(){}
// prints {}
console.log(Object());
// prints []
console.log(Array());
// prints undefined
console.log(Custom())
// prints {}
console.log(new Custom());
I know that the Custom function constructor needs a new keyword prefixed to bind this. Why isn't that necessary for Array and Object constructors ?
The array constructor says:
also creates and initializes a new Array object when called as a function rather than as a constructor. Thus the function call Array(…) is equivalent to the object creation expression new Array(…) with the same arguments.
The object constructor says:
If NewTarget is neither undefined nor the active function, then
a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%Object.prototype%").
If value is undefined or null, return ! OrdinaryObjectCreate(%Object.prototype%).
Return ! ToObject(value).
So it's explicitly noted that new isn't required for either of those.
(though, you should probably never be using either Object or Array as constructors, whether with or without new - better to use object and array literals)
It'll be trivial to implement this sort of thing yourself in Custom, if you want - check if the function was called with new, and if not, explicitly return something:
function Custom(){
if (!new.target) {
return new Custom();
}
}
console.log(Custom())
console.log(new Custom());
Custom, Object, and Array all are functions. When you call them, i.e. Object(), the value printed is the return value of the function. Object and Array returns a new empty object and array respectively. While the Custom function returns nothing and thus undefined is printed.
When you call a function with new is creates an object by calling the function as a constructor. As one of the comments mentioned This gives more details about the new keyword.
Please I want someone to explain the code below for me:
var f = new Number(44);
f.name = "Yusuf";
f.hello = function() {
console.log("Hello");
};
console.log(typeof f);
f.hello();
console.log(f.name);
console.log(f.toString() + "good");
console.log(Object.prototype.hasOwnProperty(name));
console.log(f.hasOwnProperty(hello));
console.log(f.length);
When I check the variable type. Object gets return and I am sure this is because of the Number object constructor call function. I added two properties, one a member and a method and when I call them , it work but when I used hasOwnProperty(), false is return for the member key and undefined for the method key.
Why is it so?
where are the methods going to if the hasOwnProperty doesn't work as usual when it is supposed to when I am actually checking the property on the containing object.?
I checked Number and object object and they all return false.
The hasOwnProperty method takes the property key as a string:
console.log(Number.prototype.hasOwnProperty("name"));
console.log(Object.prototype.hasOwnProperty.call(f, "name"));
console.log(f.hasOwnProperty("name"));
console.log(f.hasOwnProperty("hello"));
I recommend to always "use strict" mode so that you get exceptions when you try to use undeclared variables.
i just tried the following way of having a function assigned for a object. It works on chrome(43.0) but does not work on firefox(36.0.4)
code:
var obj = new Object();
obj.name = "Andrew";
obj.age = 20;
obj.print = function(){
console.log( this.name );
console.log( this.age );
}
obj.print(); // printing undefined in Firefox
I know of other ways of adding a function to an object such as Object.getPrototypeOf() and Object.defineProperty() but those are for json objects i suppose. The code sample above uses the object constructor, i want to know how to add a method to an object created with the object constructor. If its just not possible to have methods in an object created with the object constructor, let me know of that too. I know how to use JSON and get the methods within it or use call and apply, this is just for finding out if there is a way to add a method for objects using the new Object() constructor.
Thank you.
In firefox the function prints out "Andrew" and "20" as you'd expect.
It does also print out undefined but thats just because you function has no return value.
it's nothing to worry about, firefox is just letting you know, chrome isnt because it wont cause any issues.
if it something that worries you, have the function return true
obj.print = function(){
console.log( this.name );
console.log( this.age );
return true;
}
it will now show true in firefox instead of undefined
Also make sure that you have Log tunred on in your dev tools log level, if Log is ruened off, you'll only see the undefined messages.
Have you tried declaring the object like this? :
var obj = {
name : "Andrew",
age : "20"
}
OK, I really have read everything I can find trying to get a comprehensive understanding of Javascript. I know this can be done using a constructor function, but I'm trying to understand the language enough to know why this happens...
PeepClass = { color: "Yellow", shape: "Chick" };
var peepsA = new Object(PeepClass);
var peepsB = new Object(PeepClass);
if ( peepsA == peepsB )
document.write( "Why wouldn't these be unique instances?" );
Why doesn't new Object(PeepClass) create unique instances of the PeepClass object? Instead, it results in three references to the same object.
I guess you want this:
var peepsA = Object.create( PeepClass );
Now peepsA is a new object which inherits from the object PeepClass.
Btw when you pass an object into new Object(), that same object is returned, ergo, the operation is a no-op.
PeepClass === new Object( PeepClass )
which means that the notation new Object( obj ) is meaningless.
To put it another way, you can initialize an object in two ways:
// these are equivalent
var o1 = new Object();
var o2 = {};
To quote MDN:
The Object constructor creates an object wrapper for the given value.
If the value is null or undefined, it will create and return an empty
object, otherwise, it will return an object of a type that corresponds
to the given value.
In other words, when you call new Object(PeepClass) what you get back is not an instance of PeepClass, but PeepClass itself.
Read about new Object([value]) construction in ECMAScript standart. If value is ECMAScript object then it doesn't create a new object, it just return the value.