简体   繁体   中英

Variable not being set with return value

class Person
  constructor: (@name, @org, @phone, @email) ->
    alert "#{name}: #{org} #{phone} #{email}"

__create = (title) ->
  p =
    name: ""
    org: "_organization"
    phone: "_phone"
    email: "_email"

  (p[pr] = "%#{title}#{p[pr]}%" for pr of p)

  Person(p.name, p.org, p.phone, p.email)

m = __create "author"

alert m.name

This consistently gives me:

TypeError: Cannot read property 'name' of undefined

However, the compiled JavaScript clearly assigns m a value:

__create = function(title) {
  var p, pr;
  p = {
    name: "",
    org: "_organization",
    phone: "_phone",
    email: "_email"
  };
  for (pr in p) {
    p[pr] = "%" + title + p[pr] + "%";
  }
  return Person(p.name, p.org, p.phone, p.email);
};

m = __create("author");

alert(m.name);

What am I missing here?

You need to use the new operator, eg,

__create = (title) ->
  p =
    name: ""
    org: "_organization"
    phone: "_phone"
    email: "_email"

  (p[pr] = "%#{title}#{p[pr]}%" for pr of p)

  new Person(p.name, p.org, p.phone, p.email)

http://coffeescript.org/#classes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM