Да, но ваш синтаксис немного отключен.Когда вы создаете свойство, назначенное функции, вы не добавляете ()
, потому что это вызовет функцию.
Позже, когда вы будете готовы вызвать функцию, хранящуюся в свойстве, вы делаетеиспользуйте ()
, чтобы вызывать функцию как «метод» объекта.
Суть в том, что в JavaScript мы можем ссылаться на на функциипросто произнося их имя, и мы можем вызывать функции, произнося их имя с последующими скобками.
function runFunc(){
console.log("hello");
}
// Create new object and assign the function to a property
obj= { func: runFunc }; // <-- No parenthesis after function name here
obj.func(); // Call function as a "method" of the object
// Or, combine the above and create the property and assign the function at once
// Notice here that the function is anonymous. Adding a name to it won't throw
// an error, but the name is useless since it will be stored under the name of
// the object property anyway.
obj.otherFunc = function(){ console.log("Hello from other function! ") };
obj.otherFunc(); // <-- Here, we use parenthesis because we want to call the function