Javascript 学习记录

1. this

UISmartMonkey.prototype.RELEASE_SMARTMONKEY = function() {
    // ...
    // 设定定时任务
    var t=this;
    setInterval(10000, function() {
        if (t.getPageName() != t.commonData.pageName.liveHome && t.getPageName() != t.commonData.pageName.liveDetail) {
            t.openPageWithUrl(t.commonData.pageUrl.liveHome);
        }
    });
    // ...
}

UISmartMonkey.prototype.getPageName = function() {
    // ...
}

UISmartMonkey.prototype.openPageWithUrl = function(url) {
    // ...
}
  • 这里来解释一下,为何需要var t=this;
  • 在全局函数中,this等于window;在某个对象的函数中,this等于这个对象;在匿名函数中,this指向的也是window;
  • 上面setInterval中的function()是个匿名函数,如果直接调用this.getPageName(),会报错:Can't find variable: this;
  • 将this赋值给t,这样就可以在function中调用t访问到当前实例
  • 具体见《JS高程》P182

2. || {}

var DYUI = DYUI || {};
  • 如果DYUI是null或者undefined(其实还有0,"",false这三种情况),则将DYUI初始化为空对象
  • 有种 ifndef define endif 的感觉

3. 立即执行函数

(function() {
    DYUI.namespace = function() {
        // ...
    };
})();
  • 这是个立即执行函数
  • 函数定义外面的一层括号起到将函数声明转为函数表达式,因为只有函数表达式才可以使用括号调用
  • 后面那个括号就是表示调用

4. namespace

(function() {
    DYUI.namespace = function() {
        var a = arguments, o = null, i, j, d;
        for (i = 0; i < a.length; i = i + 1) {
            d = ("" + a[i]).split(".");
            o = DYUI;
    
            for (j = (d[0] == "DYUI") ? 1 : 0; j < d.length; j = j + 1) {
                o[d[j]] = o[d[j]] || {};
                o = o[d[j]];
            }
        }
        return o;
    };
    
    DYUI.namespace('consts');

    DYUI.consts.OP = Object.prototype;
    DYUI.consts.FUNCTION_TOSTRING = '[object Function]';
    DYUI.consts.ARRAY_TOSTRING = '[object Array]';
    
    // ...
}
  • 这是参考了YUI(Yahoo User Interface Library)中对于namespace的写法,简单来说,定义了这个namespace之后,就可以用DYUI.namespace('consts')来申明一个consts的命名空间

5. Object.prototype.toString.apply()

DYUI.consts.OP = Object.prototype;
DYUI.consts.FUNCTION_TOSTRING = '[object Function]';
DYUI.consts.ARRAY_TOSTRING = '[object Array]';

isFunction: function(o) {
    return (typeof o === 'function') || DYUI.consts.OP.toString.apply(o) === DYUI.consts.FUNCTION_TOSTRING;
},
  • js中检测类型有这么几种办法:
    1. typeof
      • 用法:alert(typeof arr);
      • 缺点:只能区分基本类型number,string,undefined,boolean,object五种
    2. instanceof
      • 用法:alert(person instanceof Array);
      • 缺点:只能被动是去判断是不是某类型,但是不能主动知道类型
    3. Object.prototype.toString.apply() / Object.prototype.toString.call()
      • 用法:
function isFunction(it) {
    return Object.prototype.toString.apply(it) === '[object Function]';
}

6. &&

this.index == oBtn.length - 1 && (oDiv.style.cssText = "");
  • 这段代码一开始没看懂,原因是对&&的语法不熟悉
  • 对于a && b js会顺序执行,先判断a是否为true,若是则继续执行b;若不是则不再执行,于是上面这行代码可以改成如下写法:
if (this.index == oBtn.length - 1) {
    oDiv.style.cssText = "";
}
  • 于是这句就可以理解了,它实现的是重置功能,即将原来加的css样式都清空

7. 函数声明不能放在 $(document).ready()里面

// 
                    
                    

你可能感兴趣的:(Javascript 学习记录)