javascript - 函数的自定义原型(prototype)链

标签 javascript prototype ecmascript-5

我只是好奇我是否可以将一个对象包含到函数原型(prototype)链中。我的意思是:

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

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

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

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

关于javascript - 函数的自定义原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597421/

相关文章:

JavaScript Getters 和 Setters 问题

javascript - [97,98].map(String.fromCharCode) 的奇怪输出

asp.net-mvc - 如何更改 ASP.NET MVC 中静态脚本文件的内容类型?

javascript - 如何使用时刻格式格式化时间段?

javascript - 使用原型(prototype)与直接在构造函数中定义方法相比有何优点?

javascript - 动态创建的 SVG 呈现为 HTML 但未正确显示

Javascript 原型(prototype)类继承

javascript - 如何在没有模块支持的情况下使用 ember.js

javascript - 使用 JavaScript/P5.js 访问数组中随机元素的不同选项

php - ajax表单提交的编码问题