整個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特別的痴迷。也希望自己能有更多的進步!