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();

但事实并非如此。方法内部的另一个函数,还有一个间隔。我想这两个把事情搞砸了。就像它不认识一样this.elm。由于我是新手,我无法找到解决此问题的方法。有任何想法吗?

小提琴

4

1 回答 1

0

您应该在代码中尝试一些 console.log 语句。在 Chrome 或 Firefox(最好安装了 firebug 插件)中时,您可以按 F12 打开控制台并查看日志输出。

console.log(this)

在 changeDisplay 中会显示this最有可能是Window. 要了解为什么您必须了解thisJavaScript 中的含义。我喜欢称它为函数调用对象,因为它最准确地描述了它(在我看来)。有关更多详细信息,请参见此处

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 并运行上面的代码。它应该工作。更多关于原型属性和实例属性之间的区别here

于 2013-10-24T02:17:03.163 回答