Domanda

sto ottenendo un errore "TestFunc non è definito" quando questo pezzo di codice ...

/* my_object.js */
"use strict";
function MyObject (param) {
    this.param = param;
}

MyObject.prototype.TestFunc = function () {
    console.log ('in TestFunc');
}

MyObject.prototype.RealFunc = function () {
    // I have tried 3 different ways to call TestFunc:
    // 1.
    this.TestFunc ();

    // 2.
    TestFunc ();

    // 3. (I didn't really think this would work,
    //     but thought it was worth a try...)
    MyObject.TestFunc ();
}

... viene eseguito da questo pezzo di codice:

/* index.js */
var myObj = new MyObject ('test');
myObj.RealFunc (); // Firebug: "TestFunc is not defined"
È stato utile?

Soluzione

// 1.
this.TestFunc ();

Va bene. Questo sarà il lavoro, con le altre chiamate rimossi.

(Beh, funziona fino a quando non staccare la RealFunc dal suo proprietario e chiama da sola, come var method= myObj.RealFunc; method(); o tramite un gestore di eventi o di timeout. In tal caso this in RealFunc non sarebbe la MyObject istanza e avresti bisogno di guardare chiusure o Function.bind per farlo funzionare.)

// 2.
TestFunc ();

No, TestFunc non è definita come variabile in ambito locale o globale. Questo fa sì che l'errore che si ottiene da Firebug.

// 3. (I didn't really think this would work,
//     but thought it was worth a try...)
MyObject.TestFunc ();

No, avevi ragione. :-) Sarebbe MyObject.prototype.TestFunc.call(this), fatto in modo esplicito.

JavaScript non sorta di confondere la questione mettendo alcuni degli stessi metodi delle funzioni di costruzione standard, per built-in oggetti come i loro prototipi (ad esempio esiste String.split dove davvero solo String.prototype.split dovrebbe). Ma questo non accada a meno che i propri oggetti dici esplicitamente qualcosa come MyObject.TextFunc= MyObject.prototype.TextFunc.

Altri suggerimenti

Variante 1 sembra corretto. Ho provato il codice in ExecuteJS e saltato 2. e 3., ha funzionato (anche se ho tolto la chiamata a console.log e cambiato in alert). TestFunc si chiama all'interno RealFunc.

Che cosa succede se si rimuove "use strict";?

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top