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.
Related
This question already has answers here:
How does JavaScript .prototype work?
(26 answers)
Closed 8 years ago.
Does the prototype in Javascript signify a method that is added to the object? I have been working on object Javascript for a little while and sometimes I see the world prototype.
Maybe a better question would be when is the prototype used in the function. By default I think that all functions have a default prototype property that is what is used in the object. A function is created just like a class in C++ or Java. And then the NEW keyword is used to create the class which is made out of the function.
Code Here:
function Sprite(url, pos, size, speed, frames, dir, once) {
this.pos = pos;
this.size = size;
this.speed = typeof speed === 'number' ? speed : 0;
this.frames = frames;
this._index = 0;
this.url = url;
this.dir = dir || 'horizontal';
this.once = once;
};
Sprite.prototype = {
update: function(dt) {
this._index += this.speed*dt;
},
Code here:
var pressedKeys = {};
This is a simple declaration of an object, correct? I think there are several ways to declare an object in Javascript but this seems to be the most common way.
More Code: In the following code were would the prototype property come to use. I am just not certain why and where the prototype property should be used.
<script>
function MyObject1() {
this.a = 1;
this.b = 2;
this.myMeth = function Fart() {
alert("hello");
}
}
var a = new MyObject1();
var b = new MyObject1();
document.writeln(a.a);
document.writeln(b.a);
a.myMeth();
</script>
The prototype chain is how you associate a method with a given type instead of just a specific instance of an object.
It's beneficial for performance reasons since you don't have to redefine the method for every instance since it's defined once at the type level.
Example using prototype:
var car = function(){
};
car.prototype.start= function(){
};
var myCar = new car();//all car objects will have the start function defined.
Example where prototype is not used:
var car = {};
car.start = function(){};
The biggest difference here is that the second example doesn't take advantage of the prototype, and is instead just tacking on a start method to the current instance only.
In the first example all created instances will have access to the start method.
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 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.
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
This may not be possible (or might be dead easy! :) ) so here it is...
I want to be able to create objects of a type that is dependant on a variable set, without the need for a big switch statement.
I think it is possible in PHP to do something like...
$objectType = "myNewClass";
$newObject = new $objectType();
where the $newObject variable will hold an instance of the Class "myNewClass".
Is this (or any similar technique) possible with Javascript?
Thanks
Stuart
If your constructor functions are defined in the global scope, you can access it trough the bracket notation (window[fnName]):
function ObjectType1(){ // example constructor function
this.type = 1;
}
var objectType = 'ObjectType1'; // string containing the constructor function name
var obj = new window[objectType](); // creating a new instance using the string
// variable to call the constructor
See: Member Operators
CMS's answer is good, but in EXT you're probably dealing with namespaces.
I create an object map that holds any dynamic classes:
// within a namespace:
var ns = {
Thinger: function(){}
};
// globals:
var Zinger = function(){}
// map:
var classes = {
zinger:Zinger,
thinger:ns.Thinger
};
var type = "thinger";
var myClass = new classes[type](props, type, etc);
Should be doable using eval():
var obj = eval("new " + objectType + "()");