javascript - 如何在 Javascript 中使用对此的新引用调用父定义的 block

标签 javascript object inheritance hash

如果我在 JS 中有一个父对象,它有一个 block 保存到一个键,我如何在嵌套对象中调用它并正确引用“this”。

var colors = {
    foo: function () {
         return this.color;
    },

    red: {  
        color: 'red',
        myColor: function () {
            return foo();
        }
    },

    blue: {
        color: 'blue',
        myColor: function () {
            return foo();
        }
    }
};

这就是我所说的

colors.blue.myColor(); 

输出为

"blue"

我使用这个想法的确切上下文是

    var accounts = {
      checking: {
        balance: 0,
        deposit: function (amount) {
            if (amount > 0) {
                this.balance += amount;
            }
        },
        withdraw: function (amount) {
            var tA = accounts.totalAmount();
            if (amount > 0 && amount <= this.balance) {
                this.balance -= amount;
            } else if (tA >= amount) {
                accounts.savings.withdraw(amount - this.balance);
                this.balance = 0;
            }
        }
      },

      savings: {
        balance: 0,
        deposit: function (amount) {
            if (amount > 0) {
                this.balance += amount;
            }
        },
        withdraw: function (amount) {
            var tA = accounts.totalAmount();
            if (amount > 0 && amount <= this.balance) {
                this.balance -= amount;
            } else if (tA > amount) {
                accounts.checking.withdraw(amount - this.balance);
                this.balance = 0;
            }
        }
      },

      totalAmount: function() {
        return accounts.savings.balance + accounts.checking.balance
      }
    };

我想在储蓄和支票之外提取存款功能,而是调用 block 。

最佳答案

您是否尝试过将值传递给 foo()?

var colors = {
    foo: function (t) {
         return t.color;
    },

    red: {  
        color: 'red',
        myColor: function () {
            return colors.foo(this);
        }
    },

    blue: {
        color: 'blue',
        myColor: function () {
            return colors.foo(this);
        }
    }
};

colors.blue.myColor(); 

关于javascript - 如何在 Javascript 中使用对此的新引用调用父定义的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26457729/

相关文章:

javascript - 使用 iframe 自动调整 Fancybox 的内容大小

javascript - 以编程方式模拟空格键,然后在文本输入字段上退格

javascript - CKEditor 插件 - 确定按钮权限错误

object - PowerShell对象值之间的关系

java - 一个例子中父类(super class)不能转换为子类,而另一个例子中可以顺利转换。为什么?

c++ - 当派生类添加了数据成员时,派生类的构造函数应该如何在 C++ 中使用

javascript - 如何检查所有文档是否都已使用 Firebase.util 分页加载

java - 初学者 - Stack 类返回对象的引用,而不是名称

javascript - 如何在 JavaScript 中使用异步函数分配对象值

visual-studio-2008 - Visual Studio - 自动实现从接口(interface)继承的所有方法