This question already has answers here:
Static variables in JavaScript
(43 answers)
Closed 9 years ago.
I have an object in Javascript like this:
var Person = {name: "John", age:37}
I would like that the name will be statically accessible every time I make a new instance of the class while the age will always be new.
So for example:
var per1 = new Person();
Person.name = "Anton";
Person.age = 11;
per1.Name //Anton
per2.Name //11
var per2 = new Person();
per1.age //Anton
per2.age //37 ????
Is there a way to make it so that it works that way?
In order to make a propery static in javascript you can use prototype:
Person.prototype.name = "Anton"
UPDATED:
You might want to use it this way:
var Person = function(age){
this.age=age;
}
Person.prototype.name = "Anton"
var per1 = new Person(12);
console.log(per1);
Related
This question already has answers here:
What is the difference between `new Object()` and object literal notation?
(12 answers)
Closed 4 years ago.
can anyone tell me actually what it is (var abc={} <==this one is object or?) if that is object what different between var abc=new Object() and var abc={};
Another question is scanner scan =new Scanner(); is same concenpt with var abc= new Object(): ??
Objects can be defined by either of these two methods:
var abc = {};
var abc = new Object();
There is minimal difference between the two, however the first method is preferred by most.
If Scanner is of type Function then you instantiate it like so:
var scan = new Scanner();
The Scanner function might have been created like this:
function Scanner(total = 5){
this.scans = total;
}
You could use this function like this:
var scan = new Scanner();
console.log(scan); // Output: Object
console.log(scan.scans); // Output: 5
scan = new Scanner(100);
console.log(scan.scans); // Output: 100
scan.scans = 50;
console.log(scan.scans); // Output: 50
var scan2 = { scans: 5 };
console.log(scan2); // Output: Object
console.log(scan2.scans); // Output: 5
For an empty object, both var abc = {} and var abc = new Object() works but there are different approaches with different scenarios/requirements to choose the appropriate style.
You can read more at:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Go to "Creating new objects"
For
var scanner = new Scanner();
Scanner must be a function.
This question already has answers here:
Should I be using object literals or constructor functions?
(12 answers)
Javascript Object : Literal Vs Constructor [duplicate]
(2 answers)
Literal notation VS. constructor to create objects in JavaScript [duplicate]
(2 answers)
Closed 5 years ago.
Can someone tell me what is difference between:
function Customer(name, age) {
this.Name = name;
this.Age = age;
}
var cust1 = new Customer('Your Name', 20);
var name1 = cust1.Name;
var age1 = cust1.Age;
and:
function Customer() {
return {
Name: 'Your Name',
Age: 20
}
};
var cust2 = Customer();
var name2 = cust2.Name;
var age2 = cust2.Age;
It produces the same output, after all, but the mechanics are different and I am not sure why.
what's the purpose of "new" in the first one though i could just do this:
var cust1 = Customer('Your Name', 20);
var name1 = cust1.Name;
var age1 = cust1.Age;
The first uses a constructor, the second a factory function.
Constructors are functions that you invoke with the new keyword. Doing so allocates a new object for you and make this a reference to this new object so you can easily mutate it. Constructors are basically syntax sugar that mimics other OOP languages construct to create new objects.
Factories are simple functions that return a plain object. You are in charge of allocating the new object yourself and returning it.
The result is exactly the same at the difference that you can't use instanceof with objects created via a factory function.
Both have pros and cons that get beyond the subject of this question: Constructors vs Factory Methods.
The output is equal (more less) but the code behaves in two different ways
In the first case the 'function' is used as a constructor for a new Js Object
Differently in the second case the 'function' just returns an object.
There isn't a real difference between the two methods but the first is more used and recommended
console.log() the two results in:
constructor: Customer { Name: 'Your Name', Age: 20 }
return obj: { Name: 'Your Name', Age: 20 }
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 does JavaScript .prototype work?
(26 answers)
Closed 8 years ago.
Given:
var x = function () {
};
x.prototype = { abc: 25 };
Can someone explain to me what this means. Could this be done all inside a function without the .prototype?
var x = function () {
// something here ?
};
Prototypes are how the class model works in JavaScript - you've created a class x that has a property abc which defaults to 25:
var obj = new x();
alert(obj.abc); // 25
The function x is the class constructor, it is called when a new instance of that class is created and can initialize it. And that means of course that you can just set the abc property there:
var x = function()
{
this.abc = 25;
};
var obj = new x();
alert(obj.abc); // 25
This is supposedly the less efficient approach however:
You have to manipulate each object created rather than setting the property on the prototype once and forever.
The property is stored on each object and consumes memory each time, as opposed to being stored once on the prototype.
ECMAScript Harmony has a nicer syntax for defining classes and prototypes, however this one isn't implemented in any browser yet:
class x {
constructor() {
...
}
public abc = 25;
}
This is equivalent to your code defining the prototype, merely grouping related operations a little better.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Use of 'prototype' vs. 'this' in Javascript?
I donot know why some developer use javascript prototype object exactly.
so, I made a sample code below.
one using prototype object, the other plain syntax.
what is difference btwn two of them?
Is there any benefit to use prototype syntax, the first case?
Car.prototype.engine_ = 'bmw';
Car.prototype.getEngine = function(){
return this.engine_;
}
Car.prototype.setEngine = function(engine){
this.engine_ = engine;
}
function Car(){
//....
}
var myCar = new Car();
myCar.getEngine();
myCar.setEngine('benz');
console.debug(myCar.getEngine());
vs
function Car(){
this.engine_ = 'bmw';
this.setEngine = function(engine){
engine_ = engine;
}
this.getEngine = function() {
return engine_;
}
//...
}
var myCar = new Car();
myCar.getEngine();
myCar.setEngine('benz');
console.debug(myCar.getEngine());
Yes, there is a difference. Using prototype, your property or method is declared once in the Object and the same for all instances. Using direct properties/methods, these properties and method are added to every instance of the Object. So here's your Car constructor:
function Car(){this.engine = 'no known engine'};
Car.prototype.setEngine = function(val){
this.engine = val;
}
Now the method setEngine is equal to all instances of your Car, but the engine property can vary per instance. The prototypal methods are defined once and looked up via the prototype chain (see also this). In this case setEngine sets the 'engine' property of the current instance of your Car. So you can do:
var bmw = new Car, merc = new Car;
bmw.setEngine('BMW');
merc.setEngine('Mercedes');
console.log(bmw.engine); //=> 'BMW'
console.log(merc.engine); //= 'Mercedes'
AFAIK there is no difference between this ones