This question already has an answer here:
Function.call method as callback [duplicate]
(1 answer)
Closed 6 years ago.
I was looking at a question yesterday in which the poster was asking how to convert the case of an array's contents. I know that I can pass a reference to a function to map like:
function appendText (el){
return el += ' - appended text';
}
['a','b'].map(appendText); //["a - appended text", "b - appended text"]
But when I tried with
array.map(String.toUpperCase);
array.map(String.prototype.toUpperCase);
I get the error
Uncaught TypeError: String.prototype.toUpperCase called on null or undefined
Which makes it sound like the method isn't getting passed the element map would, as I understand it, be passing. Why doesn't this work?
You are not passing anything to the prototype / extension method. Simply use an arrow function to pass in the value of the array item.
To answer the logic behind the question, you simply can't pass the context-less (e.g. no this) prototype method (that is, from the base String class). map will run the function by name with the value as the first parameter (as shown with appendText(a))
function appendText (el){
return el += ' - appended text'
}
var array = ['a','b']
console.log(array.map(appendText))
console.log(array.map(a => appendText(a)))
console.log(array.map(a => a.toUpperCase()))
Related
This question already has answers here:
How to explain callbacks in plain english? How are they different from calling one function from another function?
(34 answers)
Understanding Callbacks
(3 answers)
Closed 4 years ago.
How replacer argument function extract key and value from object value and mapped it to its key and value argument in JSON.Stringify(value, replacer, space) method.
I understood that key of the object become the key parameter of the replacer function and value become value parameter of this function.
let user={name:"anup", age:22};
JSON.stringify(user,function(key,value){
if(typeof value==="string"){
return undefined;
}
return value;
},null);
Here name becoming the key of the replacer function and "anup" becoming the value of the replacer function thats fine, but my question is how this mapping is happening?
Generally we call any method by passing argument in that method call, like
function a(c,d){
// logic
}
a(2,3);
But here in stringify method we are not passing any such thing to the replacer function or callback function, then how it is getting mapped?
Actually, I'm a newbie in javaScript world, so something I'm unable to understand. If you guide me in this regard , I'll be very thankful to you.
How JSON.stringify() works internally?
Thats probably some low level, highly optimized native code. But lets assume it is just a regular JavaScript function instead, that makes things easier. The function would be defined as such:
JSON.stringify = function(toStringify, replacer) {
Now that function has to determine what toStringify is first, e.g.:
if(typeof toStringify === "object") {
In that case, the code has to go over all the objects key/value pairs:
for(let key in toStringify) {
let value = toStringify[key];
Now the code can call the replacer with those pairs:
value = replacer(key, value);
Then a string can be built up as:
result += `"${key}": ${JSON.stringify(value)}`;
Then that result gets returned.
This question already has answers here:
Add method to string class
(6 answers)
Closed 4 years ago.
So, for learning purposes I'd like to recreate the "charAt()" existing method in Javascript which tells you the position of a character in a given string. I'll call the method "CharAtX"
To do so, I've created a function with 2 parameters : The first one is the word, the second is the position, here is the code I have :
function charAtX(word,pos) {
word_split = word.split("");
return(word_split[pos])
}
console.log(charAtX("Truck",2))
So, it obviously works, if i call charAtX("truck",2), i will have "u" returned.
But my question is the following :
The original charAt can be called like such
my_word.charAt(3)
Mine can't though. Why is that and how could I change my function into a method so that I can?
You have to call charAtx function in the context of String object.So, When you call string.charAtx, this object refers to the string. You have to learn prototype and this object in jvascript.
String.prototype.charAtX = function(pos) {
word_split = this.split("");
return(word_split[pos])
}
This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.
This question already has answers here:
Why won't passing `''.trim()` straight to `[].map()`'s callback work?
(4 answers)
Closed 8 years ago.
Rather than a question, I just wanted it to be a challenge but couldn't find an answer yet.
For example, we have an array of strings
x = ['a', ' b', ' c ']
and I want to trim all the elements. I tried apply and call methods but neither worked as expected:
x.forEach(String.prototype.trim.call)
// Uncaught TypeError: undefined is not a function
x.forEach(String.prototype.trim.apply)
// Uncaught TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function
What's going on here? apply/call should take their first argument from for each function and everything seems fine.
foo.call() will call the function stored in foo.
i.e. the value of this inside call will be foo.
The function you pass to forEach gets called without explicit context, so the value of this will be the default object (window in a browser).
window is not a function, so it errors.
You can use bind to create a new function that calls a function with a specific context.
Try this,
x = ['a', ' b', ' c ']
x.map(function(item) { return item.trim() })
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
JavaScript function with ‘undefined’ parameter
I'm looking the jQuery Color source code here
http://code.jquery.com/color/jquery.color-2.1.0.js
And I found that the closure function take an undefined value as it's second parameter.
See below:
(function( jQuery, undefined ) {
var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor",
// plusequals test for += 100 -= 100
rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
// a set of RE's that can match strings and generate color tuples.
Or you can see it in the source code. Look at the second parameter.
The point I want to know is that why the second parameter is undefined?
I think it is an approach to strictly set the function to receive only one parameter.
I'm I right? Or anyone can help me out?
That's in case some other part of the code assigns some value to the undefined name. The closure is actually called with only one argument, as:
(function(jQuery, undefined) {
// ...
})(jQuery);
That ensures that undefined is actually bound to undefined within the closure.