我正在启动 Javascript,但我对对象的管理方式感到非常困惑。 关注这篇文章http://www.crockford.com/javascript/private.html ,我用这段代码做了一些测试:
var Person= function() {
// Constructor
function Person(name) {
this.name = name;
};
};
Person.prototype.hello= function() {
return "Hello I am "+this.name;
};
// Object containing other object
var Couple= function() {
// Constructor
function Couple() {
this.dad= new Person("Dad");
this.mom= new Person("Mom");
};
};
Couple.prototype.introduce= function() {
return this.dad.hello();
};
var family = new Couple();
alert(family.introduce());
我在定义引入函数的行上收到Uncaught TypeError: Cannot read property 'hello' of undefined
...
我尝试将 this 上下文保存在构造函数中,并在 hello()
和 introduce()
方法中使用它,但这没有任何改变......
我觉得自己很傻,无法做出这些简单的技巧,但我没有找到明显的解决方案......
我做错了什么?
谢谢!
最佳答案
问题是你的内部提升函数仅存在于私有(private)范围内,并且不会覆盖它的父函数,即使它共享相同的名称,因为它是新声明的
当您使用var fn = function () {}
时,它将存在于定义的位置
当您使用function fn () {}
时,它将可用于在其自身之上编写的代码,因为它已被提升
例如:
doSomething(); // will actually perform correctly because definition below gets hoisted
function doSomething () {}
<小时/>
doSomething(); // will throw error because doSomething didn't get assigned yet, even though the variable doSomething was hoisted
var doSomething = function () {};
关于Javascript对象聚合: cannot call method of inner object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34688888/