0

私のフレームワークに再び取り組んでいます。要素を点滅させるメソッドを作成したかった。メソッド内で間隔を設定する必要があります。だから私はこれがうまくいくかもしれないと思った:

var optionalSelector = "$";

(function() {
    (this[arguments[0]] = function constructor(input) {
        if (!(this instanceof constructor)) { return new constructor(input); }
        this.elm = document.getElementById(input);
    }).prototype = {
        blink:      function() {
                        function changeDisplay() {
                            if (this.elm.style.display != "none") {
                                this.elm.style.display = "none";
                            } else {
                                this.elm.style.display = "block";
                            }
                        }
                        setInterval(changeDisplay, 1000);
                    },
    };
})(optionalSelector);

そしてメソッドを呼び出す$("anElmId").blink();

しかし、そうではありません。メソッド内に別の関数があり、間隔もあります。この2つがめちゃくちゃだと思います。認識しないようにthis.elm。私は初心者なので、これを修正する方法がわかりませんでした。何か案は?

フィドル

4

1 に答える 1

0

コードでいくつかの console.log ステートメントを試す必要があります。Chrome または Firefox (できれば firebug プラグインがインストールされている) では、F12 を押してコンソールを開き、ログの出力を確認できます。

console.log(this)

changeDisplay では、this最も可能性が高いことが明らかになりますWindow。その理由を理解するthisには、JavaScript で何を表すかを理解する必要があります。私はそれを関数呼び出しオブジェクトと呼ぶのが好きです (私の意見では)。詳しくはこちらをご覧ください。

var optionalSelector = "$";
window[optionalSelector] = function constructor(input) {
  if (!(this instanceof constructor)) {
    return new constructor(input);
  }
  this.elm = document.getElementById(input);
  this.intervalid = 0;
  this.timeoutid = 0;
};
window[optionalSelector].prototype.blink = 
  function(interval, timeout) {
    this.intervalid = setInterval(this._callbacks.
      changeDisplay(this.elm), interval);
    this.timeoutid=setTimeout(this._callbacks.
      cancelInterval(this.intervalid),timeout);
    return this;
};
window[optionalSelector].prototype.cancel = function() {
  clearTimeout(this.timeoutid);
  clearInterval(this.intervalid);
  return this;
};
// I like to have callback functions (closures) in it's own
// scope so you can better control what variables
// are passed to it
window[optionalSelector].prototype._callbacks = {
  changeDisplay: function(elm) {
    return function() {
      if (elm.style.display !== "none") {
        elm.style.display = "none";
      } else {
        elm.style.display = "block";
      }
    };
  },
  cancelInterval:function(intervalid){
    return function(){
      clearInterval(intervalid);
    };
  }
};

var myBlinker = window[optionalSelector]
  ("hplogo").blink(200, 2000);
//cancel it
myBlinker.cancel();
//blink something else for 2 seconds
window[optionalSelector]("gbqfba").blink(200, 2000);

google.com にアクセスして F12 キーを押し、上記のコードを実行しました。それはうまくいくはずです。プロトタイプ プロパティとインスタンス プロパティの違いの詳細については、こちらを参照してください。

于 2013-10-24T02:17:03.163 に答える