在原型对象上添加方法小例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>
<body>
    <script>
        //给构造函数原型添加新的method方法
Function.prototype.method = function(name,func){
    if (!this.prototype[name]) { //如果当前函数的原型上没有这个name属性或方法,就给他添加
        // statement
        this.prototype[name] = func;
    }
    console.log(this); //写在return之前,否则有个蛋用
    return this;
    
    
}
//添加trim方法,调用method,在String构造函数的原型上添加,也就是在所有字符串实例的原型对象上添加trim方法,
// 方法的内容是 替换当前字符串首位的空字符
String.method('trim',function(){
    return this.replace(/^\s+|\s+$/g,'');
});

console.log(("      jj      ").trim()


/*
不用method就需要每次多手打prototype这个单词
String.prototype.trim = function(){
    console.log(this)
    return this.replace(/^\s+|\s+$/g,'');
}


*/
    </script>

</body>
</html>

 

posted @ 2016-09-23 07:58  nostic  阅读(1271)  评论(0编辑  收藏  举报