2016-11-14 202 views
1

假设我有一个带参数的函数。如何通过匿名函数为对象属性赋值?

在这种情况下,我使用matchHeight,但我的问题是一般的。

我在这样的变量中设置了所有的选项。

var options = { 
    byRow: true, 
    property: 'height', 
    remove: true, 
}; 

然后将它传递给函数:现在

$('.some_class').matchHeight(options); 

,我希望能够用函数动态评估的“删除”属性。我的猜测是用这样的东西:

var options = { 
    byRow: true, 
    property: 'height', 
    // remove: true, 
    remove: function(){ return true; } 
}; 

但是,它不起作用。什么是正确的方法来做到这一点? 更新:更清晰。 matchHeight将删除作为boolean property,而不是作为一项功能。

我的主要目的是使用函数'模拟'一个布尔值,如remove: true

+0

你是什么意思*不起作用*?该对象大致正确。它取决于它如何在'matchHeight'中消耗,而且你还没有显示这个代码。如果这不是你的代码,你不能换一个布尔函数来实现这种功能。 'options.remove' vs'options.remove()',它们的调用方式不同 – Liam

+0

'options [“remove”]'? – guest271314

+0

matchHeight需要删除为[布尔属性](https://github.com/liabru/jquery-match-height#usage) – Sebastian

回答

1

你的方法应该工作 - 请这个片段:

var options = { 
 
    byRow: true, 
 
    property: 'height', 
 
    // remove: true, 
 
    remove: function(){ return true; } 
 
}; 
 

 
function myFunc(options) { 
 
    console.log(options.remove()) 
 
} 
 

 
myFunc(options)

2

如果​​是一个函数,那么你就必须真正把它叫做:

options.remove() 

如果你想使这个工作只有​​,你必须define the property with a getter

var options = { 
 
    byRow: true, 
 
    property: 'height' 
 
}; 
 

 
Object.defineProperty(options, 'remove', { 
 
    get: function() { return true; } 
 
}); 
 

 
console.log(options.remove);

+0

谢谢。不,'remove'是一个[布尔属性](https://github.com/liabru/jquery-match-height#usage) 不幸的是,你的代码不工作 – Sebastian

+0

呃...定义“不工作”。当你点击上面的“运行代码片段”时,非常* *正在工作。 – deceze