【问题标题】:functions as a property in objects : referencing other properties inside of your function [duplicate]作为对象中的属性的函数:引用函数内部的其他属性[重复]
【发布时间】:2016-01-06 23:46:59
【问题描述】:

如果我将函数作为对象的属性,函数闭包规则是否仍然适用?我记得读过一个函数是一个对象,但我也明白一个对象不是一个函数。

更具体地说,我可以在不引用该函数中的对象的情况下获取和编辑同一对象内的其他属性吗?这是一个例子:

someObj = {
property : 44,
calculate : function(){
    property * moreproperties;
};

还是我这样做?

someObj = {
property : 44,
calculate : function(){
   someObj.property * someObj.moreproperties;
};

【问题讨论】:

  • @GOTO0——仅当函数中的 this 设置为 someObj 时才有效(例如,它被称为 someObj.calculate(),但不适用于 @ 987654324@.
  • 重复的问题不相同,但答案很合适。

标签: javascript javascript-objects


【解决方案1】:

你可以使用this关键字来做到这一点

someObj = {
property : 44,
calculate : function(){
   this.property * this.moreproperties;
};

如果您有另一个函数,例如 jQuery 中的事件回调将 this 存储到变量中

someObj = {
property : 44,
calculate : function(){
   var parent = this;
   $('#some-element').click(function() {
       parent.something * parent.somethingElse
   });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2017-01-19
    相关资源
    最近更新 更多