Monday, June 3, 2024
46
rated 0 times [  51] [ 5]  / answers: 1 / hits: 26056  / 13 Years ago, mon, september 19, 2011, 12:00:00

I just wrote some JavaScript code that follows along with what I believe to be good practice for creating an object with closure and some functions:



var myStuff = (function() {
var number = 0;
var fn = {};
fn.increment = function() { number++; };
fn.decrement = function() { number--; };
fn.getNumber = function() { return number; };
return fn;
})();

myStuff.increment();
myStuff.increment();
alert(myStuff.getNumber()); // alerts '2'


I have no problem writing code like the previous snippet. I would like to write some code with functionality similar to a OOP abstract class. Here is the result of my effort:



var myStuff = (function () {
var number = 0;
var fn = {};
fn.increment = function () { number++; };
fn.decrement = function () { number--; };
fn.doSomethingCrazy = function () { throw new Error('not implemented'); }; // I want to specify later what this does.
fn.doSomethingCrazyTwice = function () { fn.doSomethingCrazy(); fn.doSomethingCrazy(); };
fn.getNumber = function () { return number; };
return fn;
})();

myStuff.doSomethingCrazy = function () { this.increment(); this.increment(); };
myStuff.doSomethingCrazyTwice();
alert(myStuff.getNumber()); // alerts '4'


The above code snippet works, but it doesn't seem graceful. Perhaps I'm trying to force JavaScript (a functional language) to do something it isn't designed to do (object inheritance)



What is a good way to define an object in JavaScript so that a function of that object can be defined later?


More From » functional-programming

 Answers
20

Just don't define the function.



Javascript is a duck-typed language. If it looks like a duck and it quacks like a duck, it is a duck.

You don't need to do anything special to make this work; as long as the function exists when you call it, it will work fine.



If you call it on an instance that doesn't have the function, you'll get an error at the callsite.


[#90024] Saturday, September 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
turnerf

Total Points: 620
Total Questions: 101
Total Answers: 109

Location: French Polynesia
Member since Tue, Jul 7, 2020
4 Years ago
turnerf questions
;