Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to have a Javascript object obj that contains an array of other objects and is able to call their methods. I would also want any object to be able to register into the array by calling a special function of the object obj and pass a reference of itself as an argument.
Would anybody be so kind and help me with that, please? I've been having a hard time with it.
Also I thought of a simple solution where the object obj creates all the other objects but that doesn't seem to work as well...
Perhaps you mean something like this
function Invoker(arr) {
arr = arr.slice();
arr.invoke = function (methodName) {
var args = Array.prototype.slice.call(arguments, 1),
i;
for (i = 0; i < this.length; ++i)
if (methodName in this[i])
this[i][methodName].apply(this[i], args);
};
return arr;
}
var arr = [
{foo: function (a, b) {console.log('foo', a);}},
{foo: function (a, b) {console.log('bar', b);}}
];
var invkr = Invoker(arr);
invkr.invoke('foo', 'hello', 'world');
/*
foo hello
bar world
*/
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 11 months ago.
Improve this question
Let's say I have this function in JavaScript:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
b = foo(b)
console.log(b)
Since JavaScript is a call-by-sharing language there is no need to return a, the object b would have the same final value with the below code:
function foo(a) {
a.item = "four"
return a
}
b = {
item: "three"
}
foo(b)
console.log(b)
Is it bad practice to use return b for better readability even though it is not needed
Are there any downsides to returning the object?
You're correct, in your example the return statement is unnecessary, strictly speaking. Also, just as a point of clarification, while JS passes objects by reference, primitive types are passed by value.
However, it is considered a JS best practice to avoid mutating function parameters. It can very quickly get very confusing when you have many functions performing actions on the same object that is getting passed around and mutated. So, in fact, I would consider it a bad practice to write a mutating function that does not involve returning a value.
Following that idea, your example would look like:
function foo(a) {
// Copy our input (assuming 'a' only contains primitive values)
const output = { ...a };
output.item = 'four';
return output;
}
const b = { item: 'three' };
const c = foo(b);
// b is unchanged
The built-in Array.prototype.sort() method returns the array even though it's sorting it in place.
Whether this provides better readability is a matter of personal preference. But it can make it easier to work with arrays/objects that are created on the fly, e.g.
sorted_words = string.split(" ").sort();
If it didn't return the array, you'd have to do this in two steps:
sorted_words = string.split(" ")
sorted_words.sort();
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying writing a function that takes an argument the user inputs into the console, adds it to the array and returns it.
This is my code.
function Album(){
this.listPhotos=["bee", "ladybug", "caterpillar", "ant"];
this.addPhoto = function(x){
listPhotos.push("x");
console.log (x.listPhotos);
}
}
You have a few things wrong:
listPhotos.push should be this.listPhotos.push
You should be pushing the variable x and not the string x
When logging you want this.listPhotos and not x.listPhotos
function Album() {
this.listPhotos = ["bee", "ladybug", "caterpillar", "ant"];
this.addPhoto = function(x) {
this.listPhotos.push(x);
console.log(this.listPhotos);
}
}
let a = new Album()
a.addPhoto('123')
You need to reference the array that's the property of the instantiated object. In your code, the plain variable listPhotos isn't declared anywhere.
Use this to reference the calling context of the current function (which, in this situation, is the instantiated object):
function Album(){
this.listPhotos=["bee", "ladybug", "caterpillar", "ant"];
this.addPhoto = function(x){
this.listPhotos.push(x);
console.log(this.listPhotos);
}
}
const myAlbum = new Album();
myAlbum.addPhoto("anotherphoto");
Another option is to declare the array as a standalone variable inside the object (not as a property of the object), but you have to make sure you don't mix up the two methods:
function Album(){
const listPhotos=["bee", "ladybug", "caterpillar", "ant"];
this.addPhoto = function(x){
listPhotos.push(x);
console.log(listPhotos);
}
}
const myAlbum = new Album();
myAlbum.addPhoto("anotherphoto");
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 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 8 years ago.
Improve this question
Today I have found a strange way of adding 2 numbers in javascript:
Basically the call of the method looks this way: add(5)(6) and the declaration of the method is:
function add(x) {
return function(y) { return x + y; };
}
Ok, I got it. The add function does not return a number, but returns the anonymous function which adds the first number with the second. But what is the point (how it can be helpful)?
Where exactly can it be useful apart from puzzling other people or writing some sort of obfuscated malware?
Obviously, the call add(5)(6) is not too useful - you'd rather write 5 + 6, or, if it's really a function, add(5, 6).
The great benefit is in functional programming where you are supposed to pass a function around (callback!) - most prominent in the array utils. For example:
[1, 2, 3].map(add(5)) // [6, 7, 8]
You can also use this for the composition of quite complex functions, without having to deal with function expressions. If we didn't have this curried add function, in the above example we would have needed to write
[1, 2, 3].map(function(y) {
return 5 + y;
}) // [6, 7, 8]
…and that every time for each different x.
Lets have a look at a function which is bit more common in the wild, pluck:
function pluck(prop) {
return function(obj) {
return obj[prop];
}
}
This function accepts a property name and returns a new function which, given an object, returns the property of that object.
This is useful for mapping an array of objects to an array of a specific property of those objects:
var names = people.map(pluck('name'));
Now, if you just have to do this a single time, there is no need to create a dedicated pluck function. However, if you do this multiple times, it avoids code repetition.
You wouldn't necessarily use it as you've described, but perhaps if you want to pass around a function that "adds 5 to the result", you could do
var addsFive = add(5);
// some other code, perhaps passing this var to another function
var result = addsFive(6); // returns 11
This technique of "partial" function invocation is called currying - this other SO question goes into some details on how/where it can be useful, as well as provides several links to help explain the concept.
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 9 years ago.
Improve this question
Below is a piece of working code. The "= true" part is confusing to me. This is what I think is happening.
1- create empty array.
2- take the selected list items (targets) and loop.
3- if the class attributes for the target list item is not in the array then enter if block.
4- add the class attributes for the target list item and add them
to the array.
My understanding is that javascript uses "push" and jquery uses "add" to
insert items into an array. The code below does not use push or add.
var foo = [];
$($targets).each(function(i) {
if (!foo[$(this).attr('class')]) {
foo[$(this).attr('class')] = true;
}
});
The code is flawed, you'd use an object instead of an array if you want to use strings as keys:
var foo = {};
Then it checks if the key is falsy in the object, although you may want to check for strict existence with the in operator:
$targets.each(function() {
var klass = this.className; // cache, no need for jQuery
// if `foo` doesn't have the key `klass` then add it
if (! (klass in foo)) foo[klass] = true;
});
Unless the class names are numbers like "1" or "2", you can't access items inside the array that way. That said, arrays are built from objects. So for example you can do things like this:
var foo = ['a', 'b', 'c'];
foo.bar = 'hello';
foo;
//=> ['a', 'b', 'c']
foo[0];
//=> 'a';
foo['bar'];
//=> 'hello';
So what's happening is that your script is not adding those items into the actual array. Instead, it's assigning them to the array as if it was a regular JavaScript object.