构造函数中的函数返回值

Function return value in constructor

本文关键字:返回值 函数 构造函数      更新时间:2023-09-26

在Javascript中,函数可以是构造函数的参数,但我希望在创建新对象时分配一个要计算的条件值。

var obj = {
  prop: function(){ return 1; },
  prop2: "asd"
};
console.log(obj.prop);  // This prints "function() ..." 

有了这个方法,有什么方法可以使道具值为1吗?

对于那些想知道我为什么要这样做的人,我有以下代码,如果某些条件为真或假,我需要传递一个不同的偏移量参数。

$('#primary-menu > ul > li > a[href*=#]').smoothScroll(

{ preventDefault: true, easing: 'swing', speed: 700, offset: -200, exclude: ['.external a'],
    beforeScroll: function () {
        // Disable all waypoints on internal divs which are linked to from the menu
        $('#primary-menu > ul > li > a[href*=#]').each(function () {
            var element_id = MO_THEME.get_internal_link($(this).attr('href')); // Gives me ids of div's with ids like #work,#service, #portfolio etc.
            $(element_id).waypoint('disable');
        });
    },
    afterScroll: function () {
        // Enable all waypoints on internal divs which are linked to from the menu
        $('#primary-menu > ul > li > a[href*=#]').each(function () {
            var element_id = MO_THEME.get_internal_link($(this).attr('href')); // Gives me ids of div's with ids like #work,#service, #portfolio etc.
            $(element_id).waypoint('enable');
        });
    }});

您可以在实例化后更改smoothScroll插件的任何选项:

首次呼叫后设置选项

如果在已经调用.smoothScroll()之后需要更改任何选项,则可以通过传递";选项";字符串作为第一个参数,options对象作为第二个参数。

$el.smoothScroll('options', {
  offset: newValue
});