JavaScript

参考

  1. https://stackoverflow.com/questions/9959727/proto-vs-prototype-in-javascript

区别

  1. 构造函数中的prototype创建了实例对象中的属性:_proto_(隐式原型,类比python语言的_xx_)
  2. 实例对象的__proto__指向了构造函数的原型对象prototype

原形

  1. prototype其实是一个对象
    Student.prototype = {
      //手动修改构造器的指向
      constructor:Student,
      height: "188",
      weight: "55kg",
      study: function () {
        console.log("学习好开心啊");
      },
      eat: function () {
        console.log("我要吃好吃的");
      }
    };


    //原型中的方法,是可以相互访问的

    function Animal(name,age) {
      this.name=name;
      this.age=age;
    }
    //原型中添加方法
    Animal.prototype.eat=function () {
      console.log("动物吃东西");
      this.play();
    };
    Animal.prototype.play=function () {
      console.log("玩球");
      this.sleep();
    };
    Animal.prototype.sleep=function () {
      console.log("睡觉了");
    };

建议

  1. 想要改变this指向就可以使用这三个方法中的任意一个,比较推荐的是apply和call
  2. 想要改变this指向,并且想要复制一个函数或者方法,就用bind
原文地址:https://www.cnblogs.com/allen2333/p/9194530.html