JS高级——扩展内置对象的方法

基本概念

内置对象有很多,几个比较重要的:Math、String、Date、Array

基本使用

1、内置对象创建出来的对象使用的方法使用的其实都是内置对象的原型对象中的方法

(1)a并没有charAt方法,但是它的原型确有此方法

<script>
    var a = new String('hello');
    console.log(a.charAt(1));
    console.log(a);
</script>

2、所以扩展内置对象的方法,可以直接给原型对象的属性进行扩展

(1)将字符串的第一个字符转成大写

<script>
    String.prototype.toUpper = function () {
        // this[0]--会有版本兼容问题
        var first = this.charAt(0);
        first = first.toUpperCase();
        return first + this.substr(1);
    }

    var a = 'hello';
    console.log(a.toUpper());//Hello
</script>

3、简单类型使用内置对象扩展方法的问题

(1)打印简单类型,返回都是都所赋的值,他们是怎么能够获取到内置对象的方法呢?

(2)简单类型调用内置对象方法的时候,会进行一个隐式的转换

<script>
    'hello'.charAt(1);
    //====>大概隐式转换过程
    var _s = new String('hello');
    _s.charAt(1);
    _s = null
</script>

4、直接将内置对象的原型对象进行替换是系统不允许的,替换了也是白替换,在严格模式下 会直接报错'use strict'

5、所以最好的 方法是通过一个干净的中介,最后可以达到不修改原内置对象的目的

<body>
    <script>
        function Person() {

        }
        Person.prototype = new Array();
        Person.prototype.say = function () {
            console.log(1);
        }
        console.dir(new Person());
        console.dir(new Array());
    </script>
</body>
原文地址:https://www.cnblogs.com/wuqiuxue/p/8351420.html