变量未设置返回值

时间:2014-10-14 18:01:10

标签: javascript coffeescript typeerror

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

这一直让我:

  

TypeError:无法读取未定义的属性“name”

但是,编译好的JavaScript会明确指定m一个值:

__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);

我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

您需要使用new运算符,例如

__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