3

オブジェクトを関数プロトタイプ チェーンに含めることができるかどうかに興味があります。私が意味したのは:

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
4

1 に答える 1

2

関数がありますtest。これは、instanceof Functionから継承するため、たとえばFunction.prototype呼び出すことができます。test.bind

次に、関数の「プロトタイプ」プロパティをから継承するオブジェクトに設定します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

于 2012-05-15T11:21:27.923 に答える