2

JavaScript では、関数の部分適用メソッドを定義するのは非常に簡単です。

Function.prototype.partial = function partial() {
    var fn = this
    var args = Array.prototype.slice.call(arguments)

    return function() {
        var newArgs = Array.prototype.slice.call(arguments)
        return fn.apply(this, args.concat(newArgs))
    }
}

関数でうまく機能します:

var biggerThanFive = Math.max.partial(5)
assert biggerThanFive(x) === Math.max(5, x)

しかし、結果として得られる関数の「<code>this」は、元のものと同じままではありません。

function Test() {
    this.name = 'test'
}

Test.prototype.a = function(b) {
    return [this.name, b]
}

var test = new Test()

test.a('x') // ['test','x']

var b = test.a.partial('y')
b() // [undefined,'y']

これは、結果の関数を元のバインドされたオブジェクトに手動でバインドすることで修正できます。

var c = test.a.partial('z').bind(test)
c() //['test','z']

Function.prototype.partial定義内からこれを行う方法は?test.aその「<code>this」が「test」であることを明白に知っているので、どうすればこの知識にアクセスできますか?


私がエサイリヤから学んだこと:

JavaScript は、呼び出し時以外の時点では、関数内の "<code>this" が何であるかを判別しません。var d = [].concatは と変わらず、「その左側」には何もないため、呼び出しはグローバル オブジェクトでそれを呼び出しますvar d = Array.prototype.concatd()

4

1 に答える 1

1

できません。

ただし、組み込み.bindメソッドを使用してこれを行うことができます。これは、最終的に到達して解決するものです。

var b = test.a.bind(test, 'y')
b() 
//["test", "y"]
于 2013-06-26T15:06:17.920 に答える