Javascript对象聚合: cannot call method of inner object

标签 javascript oop aggregation inner-classes

我正在启动 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/

相关文章:

Javascript 给出 undefined 而不是 ex.message

javascript - 嵌套函数的返回值

javascript - 输入[类型文件]更改后,变量 imageLen 不会重置

java - 如何在不使用对象时不引用它,以便垃圾收集将其删除

从子到父导航的 C++ 聚合

javascript - 为什么我在计算 javascript 时差时得到 +1 小时?

java - 为什么是Object类的wait、notify、notifyAll方法?

oop - Object.Do something() 或 Do something With(Object)

elasticsearch - 通过文本字段聚合和排序,并在Elasticsearch中连接其他文本字段

algorithm - 如何优化大列表聚合