JavaScript对象可以有一个原型链,但也可以是一个函数? [英] Can a JavaScript object have a prototype chain, but also be a function?

查看:84
本文介绍了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?

推荐答案

基于关于元的讨论 关于类似问题我在此基于 @ alexander-mills 发布此答案原始

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对象可以有一个原型链,但也可以是一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆