Javascript OOP回调“this”适用

时间:2016-03-16 07:40:13

标签: javascript jquery oop

我在自己的callback功能上创建EACH时遇到问题。

我正在使用OOP方式来配合它。

基本上,我创建了一个模仿JQUERY习惯的javascript库。

请检查此操作:https://jsfiddle.net/6pk068ep/1/

<div class="parent">
    <p class="child">child</p>
</div>
<div class="parent">
    <p class="child">child</p>
</div>

JavaScript:

"use strict";

(function(window) {

    var i, $, $Obj, ele; // global variable

    $ = function(el, length) {
        return new $Obj(el, length); // create new object
    };

    $Obj = function(el, length) {

      ele = document.querySelectorAll(el); // get selector element 

        this.length = ele.length; // count the length of ele

        for (i = 0; i < this.length; i++) {
            this[i] = ele[i]; // loop it
        }

    };

    $Obj.prototype = { // object prototype

       each : function(fn) { // create method each just like jquery

       var arr = []; // create array to store value

       for (i = 0; i < this.length; i++) {          
         arr.push(this[i]); // push it to arr variable
         }

       fn.apply(this, arr); // IS THIS THE CORRECT WAY TO APPLY IT? 
       return this; // return this, so, it's chainable for other method

      }

    };

window.$ = $; // make dollar sign global object

})(window);

$(".child").each(function() {

    console.log(this);
    this.style.color = "red"; // not working, what's wrong with my code? is it because my "apply" wrong?

});

如何将这些.child样式颜色变为红色?

我的代码出了什么问题?

提前感谢...

1 个答案:

答案 0 :(得分:3)

当你说each()时,假设将为集合中的每个项目调用回调,所以在这种情况下你需要在for循环中调用回调。

另请注意,elei等变量不是全局变量,它们可能是您使用它们的函数的本地变量。

&#13;
&#13;
"use strict";

(function(window) {

  var $, $Obj; // global variable

  $ = function(el, length) {
    return new $Obj(el, length); // create new object
  };

  $Obj = function(el, length) {
    var ele, i;

    ele = document.querySelectorAll(el); // get selector element 

    this.length = ele.length; // count the length of ele

    for (i = 0; i < this.length; i++) {
      this[i] = ele[i]; // loop it
    }

  };

  $Obj.prototype = { // object prototype

    each: function(fn) { // create method each just like jquery
      var i;

      for (i = 0; i < this.length; i++) {
        fn.call(this[i], this[i], i);
      }

      return this; // return this, so, it's chainable for other method

    }

  };

  window.$ = $; // make dollar sign global object

})(window);

$(".child").each(function() {

  console.log(this);
  this.style.color = "red"; // not working, what's wrong with my code? is it because my "apply" wrong?

});
&#13;
<div class="parent">
  <p class="child">child</p>
</div>
<div class="parent">
  <p class="child">child</p>
</div>
&#13;
&#13;
&#13;