JS构造函数的用法和JS原型

$(function(){
    //1
    var rec = new Rectangle(5, 10);
    //alert(rec.width + "*" + rec.height + "=" + rec.area());  
    //alert(rec.hasOwnProperty("width"));
    //alert("area" in rec);
    //alert(rec.toString());
    
    //2
    var message = "hello world";
    //alert(message.endsWith("d"));
    
    //alert(Array.prototype.push);
    
    //表示的最大数字和最小数字
    //alert(Number.MAX_VALUE + " OR " + Number.MIN_VALUE);
    
    
    //3
    var n = 17;
    //alert(n.toString(2));    //其中2代表转为2进制,若将其改为16,则输出的是16进制的值s 
    
    //4
    //alert(parseInt("15",8)); //输出13,15的8进制(13 == 1*8+5*0)
    
    //5.1
    //alert(fun(5));
    
    //5.2
    //alert(fun2(5));
    
    var point = new Object();
    point.x = 1;
    point.y = 2;
    //alert(point.x + " AND " + point.y);
    //alert(delete point.x); //这一行代码有无执行会影响到下一行代码的执行结果
    //alert("x" in point);
    
    
    var arr = [1, 2, 3, 4, 5];
    //alert(arr.concat(4, [5, [6, 7]]));
    //alert(arr.slice(1, 4));    //截取数据第2个到第5个元素,包括第2个不包括第5个
    
    
    var str = "chinese";
    //alert(str.lastEndChar());
    
    //alert(location.href);
    //alert(location.search); //获取url地址?后面的参数列表
    
    //打开新窗口
    //window.open("http://www.baidu.com", "minWin", "width=400, height=350, status=yes, resizable=yes");
    
});

//JS构造函数 1
function Rectangle(w, h) {
    this.width = w;
    this.height = h;
    this.area = function () {
        //return this.width * this.height;    //写法1.1
        with (this) {    //写法1.2
            return width * height;
        }
    }
}

//设置Rectangle的原型值,若构造函数中无定义area方法,则默认使用原型
Rectangle.prototype.area = function () {
    return 5;
}

//重写Rectangle的toString方法
Rectangle.prototype.toString = function () {
    return this.width + " " + this.height ;
}

//2 查看字符串的结尾是否是以c结尾的 返回true OR false
String.prototype.endsWith = function (c) {
    return (c == this.charAt(this.length - 1));
}

//5.1 lambda写法(拉姆达)
var fun = function (x) {
    return x + x;
}

//5.2
var fun2 = new Function("x", "return x+x");

//返回字符串末尾的指定个数的字符
String.prototype.lastEndChar = function (num) {
    num = (null != num)? num : 1;
    return this.substring(this.length - num, this.length);
}

我只会编码,因为我相信代码比任何的语言表达更能让人信服!!!

 

原创来自:背着理想去流量

 

posted @ 2016-03-04 17:31  Answer.AI.L  阅读(333)  评论(0编辑  收藏  举报