JS中属性/方法调用

整个2013年都是看javascript方面的资料,不过也一直是断断续续的,今天在看书的时候看到一段代码,这段代码里面有一句让我一下子有了懵了的感觉。代码如下:

Number.method('integer', function(){
    return Math[this < 0 ? 'ceil' : 'floor'](this);  //就是这句
});
View Code

当时就是中间的那句return语句让我一愣。不过仔细看了下之后我想明白了是怎么回事。也就让我想记录下来这点很微弱的知识。

在javascript中。对象可以有很多的属性和方法,一般我们在使用属性或者方法的时候都是这样:

        function P1(name){
            this.name = name;
            this.say = function(){
                console.log('my name is %s', this.name);
            };
        }

        function P2(name){
            P1.call(this, name);
        }

        var p = new P2("Jim");

        console.log(p.name);

        p.say();      //通过点调用
View Code

我们平时大多都是通过点调用,当然这也是官方推荐的方式,不过还有另外一种方式可以调用,不用我说大家也都知道。

console.log(p["name"]);

通过“[]”引起来使用,这个方式有时候是非常有用的,比如:

        var name = "name";
        console.log(p[name]);    

这样我们可以再未知属性名称或者方法名称的时候就使用它。当然上面的这种也同样适用于对象的方法,如:

        function P1(name){
            this.name = name;
            this.say = function(){
                console.log('my name is %s', this.name);
            };
        }

        function P2(name){
            P1.call(this, name);
            this.hi = function(word){
                console.log('he say %s', word);
            }
        }

        var p = new P2("Jim");

        p["hi"]('hi');   //这样

而上面当时让我一愣的代码就是这样使用的。

2013年我对javascript特别的痴迷。也希望自己能有更多的进步!

原文地址:https://www.cnblogs.com/Dn9x/p/3513306.html