JS内置类

javascript提供内置类,包括Array,String,Function等,这些内置类提供一些属性和方法。

var a = new String("hello world");
var b = "hello world";
alert(a.length);
alert(b.length);

var c = new Array(1,2,3);
var d = [1,2,3];
c.push(4);
d.pop();
alert(c);
alert(d);

 

只要是类就会有原型,不管它是自定义还是js的内置类。我们可以修改内置类的原型,让JS的基本类型的对象获得一些有趣的功能。

Array.prototype.each=function(fun) {
    for(var i=0,n=this.length;i<n;i++) {
        fun(this[i],i);
    }
}

Array.prototype.clone=function(){
    var o=[];
    this.each(function(v,k) {
        o[k] = v;
    });
    return o;
}

Array.prototype.map = function(fun) {
    var o=[];
    this.each(function(v,k){
        o[k] = fun(v,k);
    });
    return o;
}
Array.prototype.Delete = function(a){
    var o=this.clone();
    for(var i=o.length,n=0;i>n;i--) {
        if(o[i] == a) {
            o.splice(i,1);
        }
    }
    return o;
}


var = [1,2,3,2,4,5];
var str = "";
a.each(function(v,k){
    str += k+" : "+v+"\n";
});
alert(str);
var b=a.map(function(v,k){
    return v * 10;
});
alert(a);
alert(b);
var c = d.Delete(20);
alert(c);

我们还可以重写内置类的方法:

Object.prototype.test = function() {
    alert("hello world");
}
var a = [1,2,3];
a.test();


function Dog(o) {
    this.name = o;
}
Dog.prototype.toString=function() {
    return "my name is " + this.name;
}
var f = new Dog("wangcai");
//alert(f.toString());
alert(f);  //当alert(a)的时候,自动调用了a的toString方法。在需要字符串的时候,对象会隐式地调用toString方法
f.test();

 

posted @ 2014-10-17 15:04  小刘_php  阅读(390)  评论(0)    收藏  举报