• 231 对象原型 __proto__


    1、【实例】对象都会有一个属性 __proto__ 指向构造函数的 prototype 原型对象。
    2、之所以我们对象可以使用构造函数 prototype 原型对象的属性和方法,就是因为对象有 __proto__ 原型的存在。
    3、__proto__对象原型和原型对象 prototype 是等价的。
    4、__proto__对象原型的意义,就在于为对象的查找机制提供一个方向,或者说一条路线。但是,它是一个非标准属性,因此实际开发中,不可以使用这个属性,它只是内部指向原型对象 prototype。
    【补充:5、实例对象没有prototype 属性。】
    

    <!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;
            }
            Star.prototype.sing = function() {
                console.log('我会唱歌');
            }
            var ldh = new Star('刘德华', 18);
            var zxy = new Star('张学友', 19);
    
            // 方法的查找规则: 首先先看ldh 对象身上是否有 sing 方法,如果有就执行这个对象上的sing
            // 如果么有sing 这个方法,因为有__proto__ 的存在,就去构造函数原型对象prototype身上去查找sing这个方法
            ldh.sing();
    
            // 对象身上系统自己添加一个 __proto__ 指向我们构造函数的原型对象 prototype
            console.log(ldh);
            console.log(ldh.__proto__ === Star.prototype); // true
        </script>
    </body>
    
    </html>
    

    demo:实例对象没有prototype 属性
    <!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>5、实例对象没有prototype 属性</title>
    </head>
    
    <body>
    
    </body>
    
    </html>
    <script>
        function fn() {
    
        }
        console.log(fn.prototype);  // {constructor: ƒ}
        // {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
        console.log(fn.prototype.__proto__);  // 
    
        f1 = new fn()
        console.log(f1.__proto__ === fn.prototype);  // true
        console.log(f1.prototype);  // undefined
    </script>
    
  • 相关阅读:
    JS 对象定义
    JavaScript HTML DOM 元素(节点)
    DOM 事件
    DOM CSS
    DOM HTML
    DOM 简介
    JS 验证
    JS 错误
    JavaScript Break 和 Continue 语句
    JS While
  • 原文地址:https://www.cnblogs.com/jianjie/p/12219469.html
Copyright © 2020-2023  润新知