Article View: pl.comp.lang.javascript
Article #51208Re: object + this + array = this.array is undefined
From: Cezar ikari Pokorski
Date: Sun, 11 Nov 2012 23:31
Date: Sun, 11 Nov 2012 23:31
44 lines
2081 bytes
2081 bytes
W dniu 05.11.2012 o 12:58 <witold.zywica@gmail.com> pisze:
> Witam
> Mam sobie takie coś:
> (...)
> function Question(question, explanation, type) {
> this.question = question;
> this.explanation = explanation;
> this.type = type;
> this.answers = new Array();
> this.addAnswer = function (answer, explanation, type, validator) {
> this.answers.push(new Answer(answer, explanation, type,
> validator));
> }
> }
>
> (...)
> Na stronie dostaję błąd (firebug):
> this.answers is undefined
> this.answers.push(new Answer(answer, explanation, type,
> validator));
>
> Co robie zle? Jak sprawiść aby to zadziałało?
>
Na szybko i zmeczono powiem tak:
wydaje mi się, że chodzi o to, że "this" wewnątrz addAnswer jest po prostu
innym thisem niż w Question i dlatego jest problem z
this.answers===undefined.
Zrobiłbym:
this.answers = new Array();
var that = this; // <--- myk 1
this.addAnswer = function (answer, explanation, type, validator) {
that.answers.push( // <--- myk 2
new Answer(answer, explanation, type, validator));
Powinno pomóc na podstawowy problem.
--
Nie mam weny na sygnaturkę
Technical Details
Message-ID:
<op.wnmuarqgezb3y7@sch12524.schibsted.no>Path:
mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!agh.edu.pl!news.agh.edu.pl!newsfeed2.atman.pl!newsfeed.atman.pl!news.task.gda.pl!not-for-mailReferences:
<1c16ab7f-6d7c-4b33-9c1e-8e9e776a0ddf@googlegroups.com>Show Full Headers
Complete Article Headers
Path: mbox-mo1.pugleaf.net!news-archive.icm.edu.pl!agh.edu.pl!news.agh.edu.pl!newsfeed2.atman.pl!newsfeed.atman.pl!news.task.gda.pl!not-for-mail From: "Cezar ikari Pokorski" <kontakt@ikari.pl> Newsgroups: pl.comp.lang.javascript Subject: Re: object + this + array = this.array is undefined Date: Mon, 12 Nov 2012 00:31:29 +0100 Organization: ikari Lines: 52 Message-ID: <op.wnmuarqgezb3y7@sch12524.schibsted.no> References: <1c16ab7f-6d7c-4b33-9c1e-8e9e776a0ddf@googlegroups.com> NNTP-Posting-Host: 77-255-121-143.adsl.inetia.pl Mime-Version: 1.0 X-Trace: news.task.gda.pl 1352676627 25272 77.255.121.143 (11 Nov 2012 23:30:27 GMT) X-Complaints-To: abuse@news.task.gda.pl NNTP-Posting-Date: Sun, 11 Nov 2012 23:30:27 +0000 (UTC) User-Agent: Opera Mail/12.10 (Win32) Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit