【发布时间】:2017-12-11 22:48:55
【问题描述】:
我正在通过一些 JavaScript koans 来学习语言语法,但我对这组测试感到困惑:
it("should know that variables inside a constructor and constructor args are private", function () {
function Person(firstname, lastname)
{
var fullName = firstname + " " + lastname;
this.getFirstName = function () { return firstname; };
this.getLastName = function () { return lastname; };
this.getFullName = function () { return fullName; };
}
var aPerson = new Person ("John", "Smith");
aPerson.firstname = "Penny";
aPerson.lastname = "Andrews";
aPerson.fullName = "Penny Andrews";
expect(aPerson.getFirstName()).toBe("John");
expect(aPerson.getLastName()).toBe("Smith");
expect(aPerson.getFullName()).toBe("John Smith");
aPerson.getFullName = function () {
return aPerson.lastname + ", " + aPerson.firstname;
};
expect(aPerson.getFullName()).toBe("Andrews, Penny");
});
我知道构造函数中的变量是私有的,这就是为什么即使在尝试设置 aPerson.firstname、lastname 和 fullName 之后调用 getFullName() 时仍会打印“John Smith”的原因。但随后创建了一个名为 getFullName() 的函数,然后调用函数“Andrews, Penny”打印出来。
我本来希望打印“Smith, John”,因为这个新函数是在“失败”尝试将 firstname 设置为“Penny”并将 lastname 设置为“Andrews”之后创建的。为什么要打印“Andrews, Penny”?
谢谢
【问题讨论】:
-
这不取决于
it()、expect()和toBe()的实际作用吗?你错过了一些代码吗? -
当您说它们是“私人的”时,您几乎已经确定了。如果没有二传手,您还能期待什么?
-
嗯,是的,那些作用域变量是私有的。除了在构造函数中定义的函数之外,没有其他函数能够访问它们。如果特权方法被不同的方法覆盖,这不会改变。另请注意,覆盖函数确实专门访问
aPerson属性,而不是范围内的任何变量。
标签: javascript syntax