函数的自定义原型链

Custom prototype chain for a function

本文关键字:原型 自定义 函数      更新时间:2023-09-26

我只是好奇是否可以将对象包含在函数原型链中。我的意思是:

var test = function() { return 'a'; };
console.log(test.bind(this)); // return new bound function
// changing the prototype
// in console the prototype is really set as needed
// test => new object => function prototype => Object prototype
var F = function() {};
F.prototype = Function.prototype;
test.prototype = new F();
console.log(test.bind()); // this still works and returns new bound function
test.prototype.bind = function() {
    return 'test';
};
console.log(test.bind()); // this does not work as expected -> returns new bound function instead of 'test'. When I do delete Function.prototype.bind, then console.log(test.bind) returns undefined

你有一个函数test .它是一个instanceof Function,并且继承自Function.prototype,因此您可以调用test.bind例如。

然后,将函数的"prototype"属性设置为从Function.prototype继承的对象。这意味着test的所有实例都将继承自该对象(以及 Function.prototype):

var t = new test;
t instanceof test; // => true
t instanceof Function; // => true

然后覆盖自定义原型对象上的测试属性。这样做很好,因为函数方法应该只在函数(即可调用对象)上调用:

>>> Function.prototype.bind.call({})
Unhandled Error: Function.prototype.bind: this object not callable

在使用console.log的测试中,仅对test函数应用函数方法,而不对其实例应用 Function。很好,因为他们会失败。所以,我看不出任何对象应该从Function继承的理由 - 你不能构造不直接从Function继承的函数。