0

http://jsfiddle.net/9nmfX/

var a = {
    init: function(){
        this.b.c();
    },
    b : {
        constant: 'some constant',
        c: function(){
            alert( this.constant );
        }
    }
}
a.init();

I have been writing JavaScript for short while now. It suddenly occurred to me that I have not been using this. Writing out the entire naming for each call is quite annoying and time consuming.

In the above code is the implementation of this cross-browser compatible or does anyone know if I am using this incorrectly?

4

1 回答 1

2

是的,那是跨浏览器/平台。这是 ECMAScript 的一部分,因此它适用于 Javascript 的所有实现。

请注意,它this可能并不总是引用您想要的对象。考虑:

var func = a.b.c;
func();

它调用由 引用的函数a.b.c,但this将引用window对象或null代替a.b

另一个例子:

setTimeout(a.init, 1000); // Throws an error and fails after 1 second

但:

setTimeout(a.init.bind(a), 1000); // Works as expected and
setTimeout(function(){ a.init(); }, 1000); // Works as expected
于 2013-10-15T20:35:00.100 回答