简体   繁体   中英

object oriented javascript with prototypes

I'm trying to understand this a bit more clearly. When I extend modify the each function inside the Array prototype, How does calling func(this[i]) call the function passed into Array.each.

Since the function definition is function(func) and func is the parameter.

Does func = function(i) { alert(i) } and thus func(this[i]) = { function(this[i]) { alert(this[i]) } ?

Array.prototype.each = function(func) {
  for (var i=0; i<this.length; i++) {
    func(this[i]);
  }
};

[1,2,3].each(function(i) {
  alert(i);
});

是的,function(func)基本上是带有参数'func'的匿名函数

Please note that each function in JS is just an object. So func parameter passed to the each function is an object which is a function.

So calling func(aParam) you get the func parameter (which actually is a function) and call it passing the corresponding argument.

In your example: func = function(i) { alert(i); }

Inside objects, this will assume the context of the instanced prototype (in JS every type is fundamentally an object instance of some prototype, so every type has its own prototype from which to create a new object). So, in this case, this will refer to the object created from Array prototype (that is, [1,2,3] ).

Passing an anonymous function to the method each, allows that method to pass the element at i position to the function (the callback) you passed to it.

I explain:

iter #1: this => [1,2,3] ; i => 0 ; func => (function(i){ alert(i); })(this[i]) => 1
iter #2: this => [1,2,3] ; i => 1 ; func => (function(i){ alert(i); })(this[i]) => 2
iter #3: this => [1,2,3] ; i => 2 ; func => (function(i){ alert(i); })(this[i]) => 3

You can read this[i] as [1,2,3][i] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM