This question already has answers here:
Get name of object or class
(8 answers)
Closed 8 years ago.
I would like to know how I can get the name of my custom object in javascript?
var calendarDay = function (date) {
//someCode
}
var test = new calendarDay(new Date());
console.log(typeof test); //Object
However, if I do this in Chrome:
console.log(test);
Chrome shows the exact name of my customObject. Can I do this in javascript?
You're looking for test.constructor.name. You should note however that this will only work with named functions, not function expressions wherein a variable is assigned an anonymous function.
// named function, not function expression
function calendarDay (date) {
//someCode
}
var test = new calendarDay(new Date());
console.log(test.constructor.name); //"calendarDay"
EDIT:
Big surprise, as #Bergi pointed out, it's not fully supported by IE. Check out the full compatibility table on the MDN Docs
Not sure if this could help you.
give a name for your custom function obj.
var calendarDay = function (date) {
this.name = 'calendarDay';
}
var test = new calendarDay(new Date());
console.log(test.name);
Related
This question already has answers here:
javascript two variables with same name co-exist in same object?
(5 answers)
Closed 1 year ago.
In the following code I do not understand why the last console.log does not return 'kj18', although the pro-type has been changed before that line.
Could you please provide me an explanation?
var studentId = 'ab73';
function Student() {
this.studentId = 'b0e1';
}
console.clear()
console.log(new Student().studentId);
Student.prototype.studentId = 'kj18'
Student.prototype.classId = '5e'
console.log(new Student().classId)
console.log(new Student().studentId) // why is not kj18
Because the assignment in the function Student() gets executed when you create a new instance from Student and it all happens after this assignment: Student.prototype.studentId = 'kj18'
Adding a log to the "constructor" helps explain it.
var studentId = 'ab73';
function Student() {
this.studentId = 'b0e1';
console.log('assigned b0e1')
}
console.log(new Student().studentId);
Student.prototype.studentId = 'kj18'
console.log('assigned kj18')
Student.prototype.classId = '5e'
console.log(new Student().classId)
console.log(new Student().studentId) // why is not kj18
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
I have a method which sets a new instance to an array, created dynamically. How can I do that without the use of eval()?
var Form = (function(){
function Form(params){
this.shapesArray = [];
this.shape;
...
}
Form.prototype.submit = function(){
... this.shape is the shape selected by the user ...
this.setShape('new Shapes.' + this.shape + '(arg1, arg2, color)');
}
Form.prototype.setShape = function(obj){
this.shapesArray.push(obj);
}
return Form;
}());
So, how to call the setShape method by passing new instance to it without eval()?
This works so far:
Form.prototype.submit = function(){
eval('this.setShape(new Shapes.'+ this.shape.capitalize() +'('+ str_params + '))');
}
But using eval() is not a good practice. How to achieve the same result wighout eval()?
You may use the bracket notation to access the property :
this.setShape(new Shapes[this.shape](arg1, arg2, color));
Now, if you get your arguments from a dynamic array, it's a little more complex because you can't just use apply.
Here's a solution:
var constructor = new Shapes[this.shape];
var C = function(){
return constructor.apply(this, arr_of_args);
}
C.prototype = constructor.prototype;
this.setShape(new C());
But this starts to get tricky and hard to read. A new design of your application not involving dynamic constructors having a variable number of arguments might be preferable.
This question already has answers here:
how to access object property using variable [duplicate]
(2 answers)
Closed 7 years ago.
I am trying to use a variable to select from an array:
This works:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
But this does not work:
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
var myvalue = "bricks"
function Two() {
alert(myarray.myvalue);
}
How do I do this properly? Here is a fiddle to show what I am trying to accomplish: https://jsfiddle.net/chrislascelles/xhmx7hgc/2/
Use the [] notation.
var myarray = {bricks:3000, studs:500, shingles:400, tiles:700};
function One() {
alert(myarray.bricks);
}
var myvalue = "bricks" //supplied here to make example work
function Two() {
alert(myarray[myvalue]);
}
Demo
The variable is not an array, it's an object.
To access an element from object using variables you should use Bracket Notation like bellow
alert(myarray[myvalue]);
Fiddle
The only thing you are lacking is the syntax. Here is how it works:
function Two() {
alert(myarray[myvalue]);
}
In javascript, it means the same thing to write these two:
var a = {};
a.foo = "hello";
a["bar"] = "world";
a.bar; // world;
a["foo"]; // hello;
This question already has answers here:
Is there a better way to do optional function parameters in JavaScript? [duplicate]
(28 answers)
Closed 8 years ago.
In PHP I can do something like this:
public myFunction($variable=0) {
//Do some stuff
}
In Javascript, the following does not work:
var myFunction = function(variable=0 )
{
//do some stuff...
};
Try this
var myFunction = function(variable) {
variable = variable || 0;
// this variant works for all falsy values "", false, null, undefined...
// if you need check only undefiend, use this variant
// variable = typeof(variable) == 'undefined' ? 0 : variable
};
Default function parameters will be in ES6; ES5 does not allow it.
With ECMAScript 6 you can do this.
Check an example:
function multiply(a, b = 1) {
return a*b;
}
multiply(5); // 5
But this is still experimental and today is only supported by Mozilla Firefox browser.
Check this link do see documentantion:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters#Browser_compatibility
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript type of custom object
I have a question regarding JavaScript instances.
Let us consider the following code:
function Box(col)
{
var color = col;
this.getColor = function()
{
return color;
};
}
var blueBox=new Box("blue");
console.log(blueBox.getColor())
var greenBox=new Box("green");
console.log(greenBox.getColor())
console.log(typeof(blueBox))
console.log(typeof(greenBox))
Now, when we check the last two statements, the browser prints type as object
How do I check If they are created from same constructor Box?
You can use instanceof like:
var blueBox=new Box("blue");
if (blueBox instanceof Box){
//yay 4 boxes!
}
In case you want to check two elements you can also compare their constructors:
var blueBox = new Box("blue");
var greenBox = new Box("green");
if (blueBox.constructor === greenBox.constructor){
//yay 4 same constructors
}
use instanceof
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/instanceof
Your custom object Box is an object as far as javascript is considered, however it can be an instance of a Box which is of type object.