Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
In javascript, we can initialise a variable with {}. What does the "{}" mean?
var o = {};
o.getMessage = function ()
{
return 'This is an example';
};
return o;
This means you create an object with a variable
Its known as object with literal notation.which seems like below .
var o = {}
here your object has no property or it can be say as empty literal block .But in the below code
var o = {
o .first= 20;
o .second= 10;
o.result =function(){
return this . first- this .second;
}
} ;
now you have your object with property and function
** though there are several ways of creating object But Literal notation is the easiest and popular way to create objects
Basically the different cases are:
Use {} instead of new Object()
Use "" instead of new String()
Use 0 instead of new Number()
Use false instead of new Boolean()
Use [] instead of new Array()
Use /()/ instead of new RegExp()
Use function (){} instead of new Function()
Basically, it is an empty object. When you add the getMessage() function at the bottom of the variable, you actually added it to the empty object, resulting to your empty object now to look like this:
var o = {
getMessage: function() {
return 'This is an example';
}
};
You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
For example I have to add 'foo' to string.
So I have at least two ways to go.
First, I can implement String.prototype.foo:
String.prototype.foo = function() {
return this + 'foo';
};
var s = 'str';
var data = s.foo(); // "strfoo"
Another way:
function foo(str) {
return str + 'foo';
}
var s = 'str';
var data = foo(s); // "strfoo"
Both look pretty. But should I think about any "underwater rocks" before choosing first or second implementation? Are there any significant reasons, such as efficiency and performance?
The first extend the functionalities of String.
Use this solution if you have a class of objects and you like to add new behaviours to it.
The second is more an utility function.
Note also that you can apply the second foo also to a variable that is not a String, so you should also test the type of the argument if you like to limit the use to a String argument.
Modifying the globals in JavaScript is always a bad decision. Don't do that, except if it's not about making a polyfill.
The implications are multiple from your code being not portable to probability of breaking someone else's code.
I would always use the second method. Or if things are really that complicated maybe implement my own class of String.
function MyString(str) {
this.str = str;
}
MyString.prototype.foo = function() { return this.str + "foo" };
var s = new MyString("str");
var data = s.foo(); // "strfoo"
Here is further reading about modifying global objects and the downsides :
https://softwareengineering.stackexchange.com/questions/104320/why-is-extending-the-dom-built-in-object-prototypes-a-bad-idea
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to parse an array from one function ton another.
I have seen in other posts that ".apply" can be used as in this example:
var x = [ 'p0', 'p1', 'p2' ];
call_me.apply(this, x);
But in my code I want to parse to other function not just one array, I want to parse the array and two strings more. So mi code looks more like:
var array = [1, 2, 3];
var string = "something":
var string1 = "something":
ShowM(array, string, string2);
function ShowM(array, string1, string2) {
alert(array[1] + string1 + string2);
}
Is there any way to do that without changing the original location of the elements of the arrays for not getting undefined?. Thnks
If the question is purely about how do you set an array as a parameter in Javascript as your topic question states, you just do like any other variable.
var array = [a,b,c];
var str = "hello";
var str2 = "something";
function foo(x,y,z) {
// do stuff...
}
foo(array, str, str2); //executes function with the 3 parameters
If you just want to pass the array into a function, you can pass it as you would any other variable:
function showM(a, b, c) {
// empty function definition
}
var x = [ 'p0', 'p1', 'p2' ];
showM(x, "some string", "another string");
All arrays are passed by reference in javascript, so when you alter a passed array's contents within the function, the contents will change across all scopes. And duck-typing means that you can use any variable type as an argument.
The apply function, on the other hand, calls a function with a given content and an array of arguments (which it expands, like with the ES6 spread operator):
// equivalent to the other call, except "this" is bound to null
showM.apply(null, [x, "some string", "another string"]);
This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 8 years ago.
Hello I have an object:
var equippedItems = {
weapon: {},
armor: {},
accessory: {}
};
I need a way to check if equippedItems.weapon equals to '' at some point I am doing something like equippedItems.weapon = ''; I dont know if it's exactly the same as above object. I already tried using object.hasOwnProperty but it seems I cannot use equippedItems.weapon in this case, maybe I am doing something wrong? Also note I did read how to check if object is empty already, but it didn't work for my object inside an object.
#Edit:
Like I said, I already read those and they did not give me a straight answer for my question, they did answer how to check if object is empty, but the object was like object = {}; while mine is like
object = {
object:{},
object2:{},
object3:{}};
Thats why it confuses me.
Just make use of Object.keys
function isEmpty(obj, propName){
return Object.keys(obj[propName]).length == 0;
}
Another way is to make use of JSON.stringify method which will return {} if empty
function isEmpty(obj, propName){
return JSON.stringify(obj[propName]) == "{}";
}
In both the cases, you would call the function like
if(isEmpty(equipmentItems.weapons)){
equipmentItems.weapons = "";
}
To check that an object has a property you can use:
"weapon" in equippedItems
or
equippedItems.hasOwnProperty("weapon")
This question already has answers here:
How to execute a JavaScript function when I have its name as a string
(36 answers)
Closed 8 years ago.
This question is already existing in a different way, but my code is mostly different so I dont get the solution out of the other answers. That's a example Code:
http://jsfiddle.net/e52n28xs/
I want start the function like this:
var test1 = {
start: function() { }
};
var fn = 'test1';
fn.start();
I know the following works, but I need the string option.
test1.start();
Maybe that's impossible?
You could do it with eval() function
var test1 = {
start: function() { }
};
var fn = 'test1';
eval(fn).start()
DEMO
Depending on the value of this in the function you run this, either of these will work:
window['test1'].start();
Or
this['test1'].start();
Obviously, you can do the same with the function name itself, example:
test1['start']();
or
this['test1']['start']();
// same as: var test1 = this['test1']; test1['start']();
If you want the whole thing to be string, then:
eval('test1.start()');
That would also work if you are using var, where in the previous string versions you'd have to have a container object to query.
This question already has answers here:
Adding Prototype to JavaScript Object Literal
(5 answers)
Closed 9 years ago.
If I have an object like this:
var obj = {};
I can't extend it because it hasn't got any prototype.
Is there any way to convert this object to dynamic so that it's possible to extend it and use new keyword. Something like:
obj.prototype.property = 'value';
var newobj = new obj;
That has nothing to do with static or dynamic.
You can only use the new operator on functions, not objects.
You cannot turn an object into a function; you need to create it as a function in the first place.
the only way is the following:
var obj = function () {};
because you can only use the new keyword with constructor function. That's it!