>  Q&A  >  본문

javascript - JS原型链

    var Human = function (name) {
        this.name = name;
    }

    Human.prototype.sayName = function () {
        console.log(this.name);
    }

    var klam = new Human('klam');

输出 Human.__proto__的时候,按理该输出Function.prototype,但再Chrome浏览器中显示: function Empty () {}
再输出 Human.__proto__.constructor,结果为:function Function() { [native code] },这没问题
最后不死心再试试 Human.__proto__.constructor.prototype,又成:function Empty() {}了。

这个function empty究竟是个什么?

黄舟黄舟2724일 전712

모든 응답(5)나는 대답할 것이다

  • PHP中文网

    PHP中文网2017-04-10 14:32:26

    function Empty(){} 就是 Function.prototype 这是一个内置的对象,是所有非host函数的原型。

    如果你对它为啥叫Empty比较好奇的话,嗯,答案是不为啥,随便起了个名,也许因为
    Function.prototype()这样执行了以后啥都不会干吧,不同引擎也不一样。

    啥叫非host函数,JS里面带有[[call]]私有方法的对象都叫函数,这样的对象分为两类:
    一类是JS语言原生的,包括Function构造器构造的、内置的、function关键字声明的或者function表达式创建的,比如function a(){}或者Math.cos这些都是原生函数;
    另一类是宿主对象提供的,比如浏览器宿主提供的setTimeout就属于host函数。


    SF原题what-is-function-empty-in-javascript
    知乎原题function Empty是一个什么样的东西

    회신하다
    0
  • 巴扎黑

    巴扎黑2017-04-10 14:32:26

    我觉得对着呢。
    对象的内部属性[[Prototype]](也就是楼主提到的proto)指向该对象的构造函数的原型对象。
    那么:

    Human.__proto__===Function.prototype;//true
    

    chrome运行结果为true。
    至于指向的东西,我也不懂。

    회신하다
    0
  • 巴扎黑

    巴扎黑2017-04-10 14:32:26

    见 ECMAScript 规范:

    15.3.4 Properties of the Function Prototype Object

    The Function prototype object is itself a Function object (its [[Class]] is "Function") that, when invoked, accepts any arguments and returns undefined. The value of the internal [[Prototype]] property of the Function prototype object is the Object prototype object (section 15.3.2.1).

    It is a function with an “empty body”; if it is invoked, it merely returns undefined. The Function prototype object does not have a valueOf property of its own; however, it inherits the valueOf property from the Object prototype Object.

    회신하다
    0
  • 天蓬老师

    天蓬老师2017-04-10 14:32:26

    proto在chrome下不能直接访问到的,想看去ff下看。

    회신하다
    0
  • 巴扎黑

    巴扎黑2017-04-10 14:32:26

    Human.proto 指的是实例化Human的原型吧 说白了Human = new Function(XXX) 然后就好理解了 我是这么认为的 具体的就不知道了


    嗯 说的有点模糊 Human是一个function同时也是Function的一个实例 proto指的是他继承的原型链而不是本身的原型链 所以Human.proto = Function.prototype

    회신하다
    0
  • 취소회신하다