js原型对象和原型链及小题解析

原型和原型链

什么是原型?

每一个构造函数里面都有一个属性叫做prototype,它的值就是一个对象,这个对象我们叫做原型对象。

什么是原型链?

每个实例对象都有一个私有属性__proto__,指向它的构造函数的原型对象,这个原型对象也有一个自己的原型对象,这个原型对象也有这个属性__proto__,它会指向这个原型对象,层层向上直到一个对象的原型对象为null。根据定义,null没有原型,作为这个原型链中的最后一个环节。

原型链

在原型链中有这样两个公式

var arr=new Array(1,2,3)
console.log(arr.__proto__===Array.prototype)
console.log(arr.__proto__.__proto__==Object.prototype)

在这里插入图片描述
下面是几个小题
第一题

              function Fn() {
            this.x = 100;
            this.y = 200;
            this.getX = function () {
                console.log(this.x)
            }
        }
        Fn.prototype.getX = function () {
            console.log(this.x)
        }
        Fn.prototype.getY = function () {
            console.log(this.y)
        }
        var f1 = new Fn;
        console.log(f1.getX());
        console.log(f1.getY());

输出结果为:
在这里插入图片描述
第二题

        function Fn(num){
            this.x=this.y=num;
        }
        Fn.prototype={
            x:20,
            sum:function(){
                console.log(this.x+this.y);
            }
        }
        Fn.prototype.constructor=Fn;
        let f1=new Fn(10);
        console.log(f1.sum===Fn.prototype.sum);
        f1.sum();
        Fn.prototype.sum()
        console.log(f1.constructor);

输出结果为:
在这里插入图片描述
第三题

        function Fn(num){
            this.x=this.y=num;
        }
        Fn.prototype={
            a:1,
            b:2,
        }
        Fn.prototype.constructor =Fn;
        let f1=new Fn(10);
        let f2=new Fn(10);
        console.log(f1.a);
        console.log(f2.a);

输出结果为:
在这里插入图片描述
第四题

      function Fn(){
          let a=1;
          this.a=a;
      }
      Fn.prototype.say=function(){
          this.a=2;
      }
      Fn.prototype =new Fn;
      let f1=new Fn;
      Fn.prototype.b=function(){
          this.a=3;
      }
      console.log(f1.a);
      f1.say();
      console.log(f1.a);
      f1.b();
      console.log(f1.a);

输出结果为:
在这里插入图片描述
第五题:

        function Fn(){
            this.x=10;
            this.y=20;
        }
        Fn.n=1000;
        Fn.say=function(){
            console.log("hello");
        }
        Fn.prototype.sum=function(){
            return this.x+this.y;
        }
        let f1=new Fn;
        console.log(f1.sum());

输出结果为:
在这里插入图片描述
第六题:

function c1(name){
            if(name){
                this.name=name;
            }
        }
        function c2(name){
            this.name=name;
        }
        function c3(name){
            this.name=name || "join";
        }
        c1.prototype.name="Tom";
        c2.prototype.name="Tom";
        c3.prototype.name="Tom";
        alert((new c1().name)+(new c2().name)+(new c3().name));

结果如下:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值