Heim  >  Fragen und Antworten  >  Hauptteil

javascript - 问个原型问题,有点蒙了

<script>

Function.pototype={
        eat:function(){
            console.log("说话");
        }
    }
    
    function Person(name,age){
        this.name=name;
        this.age=age;
        this.country=function(){
                console.log(this.name+"来自"+country);
            };
    }

    Person.eat();

</script>

    *****为什么最后报错说 eat()不是一个function啊?*****
PHP中文网PHP中文网2748 Tage vor321

Antworte allen(7)Ich werde antworten

  • PHP中文网

    PHP中文网2017-04-10 16:24:17

    改成这样吧:

    Function.prototype.eat = function(){
        console.log("说话");
    };

    Antwort
    0
  • 黄舟

    黄舟2017-04-10 16:24:17

    你在Console里面试一下就会知道,对Function.prototype赋值并没有产生效果。写完了Function.prototype还是{},所以你调用Person.eat当然会失败。

    Antwort
    0
  • 怪我咯

    怪我咯2017-04-10 16:24:17

    首先prototype打错了。。。另外我在控制台试着打印Function.prototype发现返回的是一个空函数,不是一个对象,所以你这样赋值应该是错的。

    Antwort
    0
  • 阿神

    阿神2017-04-10 16:24:17

    传送门自己看看吧

    Antwort
    0
  • 大家讲道理

    大家讲道理2017-04-10 16:24:17

    因为类似于Object.prototypeFunction.prototype等是不可以更改的,就类似与下面的这个obj对象的x属性:

      var obj = {},
          a = {x: 1};
      Object.defineProperty(obj,'x',{
          enumerable: false,
          configurable: false,
          writable: false,
          value: a
      });
      obj.x = {};
      console.log(obj.x === a);   // 还是a对象
      console.log(obj.x.x);   // 20,这个对象可以更改

    Antwort
    0
  • 怪我咯

    怪我咯2017-04-10 16:24:17

    Person.prototype.eat=function(){

            console.log("说话");
        }
    
    function Person(name,age){
        this.name=name;
        this.age=age;
        this.country=function(){
                console.log(this.name+"来自"+country);
            };
    }
    
    Person.eat();
    

    我不懂你什么意思,是这个吗

    Antwort
    0
  • 迷茫

    迷茫2017-04-10 16:24:17

    我觉得楼上几个说法倒是没错 不过楼主你新定义的构造函数貌似没有继承原型函数……楼上的答案加上我说的这个应该是可以输出了

    Antwort
    0
  • StornierenAntwort