3

最初のものは機能し、2番目のものは機能しない理由を誰かが説明できますか?

function MyObj(val) {
    this.value = val;

    this.myFunc = function(selector) {
        $(selector).html("test: " + this.value);
    }
}

foo = new MyObj("tester");
foo.myFunc("#one"); //This works

func = foo.myFunc;
func("#two"); //This doesnt

どのように?どうすればそれを機能させることができますか?

JSFIDDLE

4

2 に答える 2

4

JavaScriptの関数thisは何にも固定されていません。あなたが電話するとき

something.somefunc()
// or something['somefunc']()

thisにバインドされsomethingます。オブジェクトなしで関数を呼び出すと、(strict モードで) またはグローバル オブジェクトthisにバインドされます。undefined

右を保持する変数を保持することで、それを回避できますthis

function MyObj(val) {
    var obj = this;

    this.value = val;

    this.myFunc = function(selector) {
        $(selector).html("test: " + obj.value);
    };
}

ECMAScript 5 は、Function.prototype特にこれに対処するためのメソッド on を提供します (通常はmyFunconMyObj.prototypeも使用する必要があります)。

var func = foo.myFunc.bind(foo);
func("#two"); // Works now
于 2013-09-08T19:58:20.347 に答える
0

の値を関数bind()に割り当てるために使用します。this

function MyObj(val) {
    this.value = val;

    this.myFunc = function(selector) {
        console.log(this); // <--- look your console output
        $(selector).html("test: "+this.value);
    }
}

foo = new MyObj("tester");
foo.myFunc("#one");

func = foo.myFunc;
func.bind(foo)("#two"); //  <---- here

また:

func = foo.myFunc.bind(foo);
func("#two");

デモ: http://jsfiddle.net/M8Qym/1/

于 2013-09-08T20:03:11.210 に答える