"dot function" operator in JavaScript
I'm a total newbie in js, so please be gentle with me :)
I want to understand where can we use the dot operator on some variable (in this case - an array), and when we cannot. consider the following code:
//example 1
function f1(x) {
return x*x;
}
console.log(map(f1, [1,2,3,4,5]));
console.log([1,2,3,4,5].map(f1));
//example 2
function f2(arr) {
return arr;
}
console.log(f2([1,2,3,4,5]));
console.log([1,2,3,4,5].f2());
I know the examples are rather different, but still - in example 1 both prints work (and print the same) - even when using the array.function(..)
syntax, while in example 2 the second print raises an error. basically, what is the difference between the two, and why does it work only in example 1?
and generally - can I apply this method over different variable types (numbers, booleans, etc.)?
In the first example your are using the Array.prototype.map()
function.
This function can be called in 2 different ways (See the docs)
[1,2,3].map(function(x){ ... }): //In your case the callback function is *f1()*
OR
arr.map(callback, [1,2,3]);
The second example is not working because the class Array
has not function called f2()
[1,2,3,4,5]
is an instance of Array "class", and that "class" has map method, that's why the following is a valid code:
[1,2,3,4,5].map(f1)
map
method can accept any function as a parameter, and you're passing in your f1
function. It will be executed inside map
function and it's executed as a standalone function.
Array "class" doesn't have f2
method, that's why this is invalid code:
[1,2,3,4,5].f2()
Here, f2
is executed immediately and is a part of [1,2,3,4,5]
object
In the first case, map
is defined as both a global function and public function of the Array
. You can therefore call it via map(arr)
or arr.map(..)
In the second case, as you only defined f2 as a global function which means the array can't access it.
链接地址: http://www.djcxy.com/p/19046.html下一篇: JavaScript中的“点函数”操作符