0

I am using a build tool with ES6 support, and I have the following code:

function Message(subject, body) {
    this.subject = subject;
    this.body = body;
    this.unread = true;
}

Message.prototype.markAsRead = function() {
    this.unread = false;
}

export {Message};

Later in another file when I do this:

import {Message} from './application/Message.js';
var message = new Message("hey", "there");
message.markAsRead();

I get the following error inside of the markAsRead() method:

Uncaught TypeError: Cannot set property 'unread' of undefined

A console log of this inside that method return undefined.

Is it the way I'm importing/exporting Message? Is it something deprecated in ES6? I don't have this problem when I write ES5 JS, but I figure it's something simple that I'm doing wrong.

AgmLauncher
  • 7,070
  • 8
  • 41
  • 67
  • 2
    The quoted code is fine, perhaps you over-simplified for the question? For instance, is your real code calling `markAsRead` as a callback? E.g., `doSomethingAsync(message.markAsRead)`, because *that* would have the symptom you've described (because you lose the meaning of `this`). – T.J. Crowder Oct 31 '15 at 08:11
  • 2
    As TJ says, *this* is set by the call, so if you aren't actually calling the method as `message.markAsRead()` then you may not be setting *this* correctly. Though in non–strict mode it should default to the global object and the error would be different. – RobG Oct 31 '15 at 08:17
  • Yes, I did simplify the question, and yes, it is being used as a callback (it's actually a Vue.js call inside of `v-on:click="..."`. Looks like moving that into a dedicated wrapper method in the Vue instance resolved the problem. – AgmLauncher Oct 31 '15 at 08:17
  • 1
    @AgmLauncher please delete your question if you solved it and the description isn't even accurate. – Mulan Oct 31 '15 at 09:27

0 Answers0