js prototype原型理解 Demo (2)

版权声明: https://blog.csdn.net/qq_23521659/article/details/87933598

代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>prototype</title>
</head>
<body>
<script>
    /**
     * 当调用某种方法或查找某种属性时,首先会在自身调用和查找,如果自身并没有该属性或方法,则会去它的__proto__属性中调用查找,也就是它构造函数的prototype中调用查找。
     */
     function A(){

    }

    function B(a){

        this.a = a;

    }

    A.prototype.a = 1;

    B.prototype.a = 1;

    console.log(new A().a);

    console.log(new B().a);

    console.log(new B().__proto__.a);

    
</script>
</body>
</html>

打印控制台如下:

new A()为构造函数创建的对象,本身没有a属性,所以向它的原型去找,发现原型的a属性的属性值为1,故该输出值为1;

而new B(),本身里面是有a属性的,所以直接打印undefined;

猜你喜欢

转载自blog.csdn.net/qq_23521659/article/details/87933598