234 原型对象中this指向; 通过原型,为数组扩展内置方法

1.10 原型对象中this指向

构造函数中的this和原型对象的this, 都指向我们new出来的实例对象。

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        function Star(uname, age) {
            this.uname = uname;
            this.age = age;
        }
        var that;
        Star.prototype.sing = function() {
            console.log('我会唱歌');
            that = this;
        }
        var ldh = new Star('刘德华', 18);
        // 1. 在构造函数中, 里面this指向的是对象实例 ldh
        ldh.sing();
        // 2.原型对象函数里面的this 指向的是 实例对象 ldh
        console.log(that === ldh);  // true
    </script>
</body>

</html>


1.11 通过原型,为数组扩展内置方法

可以通过原型对象,对原来的内置对象进行扩展自定义的方法。比如给数组增加自定义求偶数和的功能。

注意:数组和字符串内置对象不能给原型对象覆盖操作 Array.prototype = {} ,只能是 Array.prototype.xxx = function() {} 的方式。
【Array 上的 "prototype" 属性的 “指向” 是不能修改的。writable属性可以用 Object.defineProperty() 自定义 所以有办法在自定义 class 上重现这个行为】

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
</body>
</html>
<script>
    // 原型对象的应用 扩展内置对象方法
    // 此时,数组对象中已经存在sum()方法了  可以始终 数组.sum()进行数据的求
    Array.prototype.sum = function() {
        var sum = 0;
        for (var i = 0; i < this.length; i++) {
            sum += this[i];
        }
        return sum;
    };

    // Array.prototype = {
    //     constructor: Array,
    //     sum: function() {
    //         var sum = 0;
    //         for (var i = 0; i < this.length; i++) {
    //             sum += this[i];
    //         }
    //         return sum;
    //     }
    // }

    console.log(Array.prototype);
    var arr = [1, 2, 3];
    console.log(arr.sum());

    var arr1 = new Array(11, 22, 33);
    console.log(arr1.sum());
</script>
原文地址:https://www.cnblogs.com/jianjie/p/12221436.html