本文介绍了JavaScript对象可以有一个原型链,但也可以是一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
function a () {
return "foo";
}
a.b = function () {
return "bar";
}
function c () { };
c.prototype = a;
var d = new c();
d.b(); // returns "bar"
d(); // throws exception, d is not a function
有什么办法吗? d
是一个函数,但仍然从 a
继承属性?
Is there some way for d
to be a function, and yet still inherit properties from a
?
推荐答案
基于 我在此基于发布此答案原始
Based on a discussion on meta about a similar question I'm posting this answer here based on @alexander-mills original
首先创建一个继承函数的对象
const obj = Object.create(Function.prototype); // Ensures availability of call, apply ext
然后将自定义方法和属性添加到 obj
Then add you custom methods and properties to obj
下一步声明函数
const f = function(){
// Hello, World!
};
并设置 obj
作为 f
Object.setPrototypeOf(f,obj);
Demonstraction
Demonstraction
const obj = Object.create(Function.prototype);
// Define an 'answer' method on 'obj'
obj.answer = function() {
// Call this object
this.call(); // Logs 'Hello, World'
console.log('The ultimate answer is 42');
}
const f = function() {
// Standard example
console.log('Hello, World');
};
Object.setPrototypeOf(f, obj);
// 'f' is now an object with an 'answer' method
f.answer();
// But is still a callable function
f();
这篇关于JavaScript对象可以有一个原型链,但也可以是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!