Are Interfaces in JavaScript necessary? - javascript

I suppose this could apply to any dynamic language, but the one I'm using is JavaScript. We have a situation where we're writing a couple of controls in JavaScript that need to expose a Send() function which is then called by the page that hosts the JavaScript. We have an array of objects that have this Send function defined so we iterate through the collection and call Send() on each of the objects.
In an OO language, if you wanted to do something similar, you'd have an IControl interface that has a Send() function that must be implemented by each control and then you'd have a collection of IControl implementations that you'd iterate through and call the send method on.
My question is, with JavaScript being a dynamic language, is there any need to define an interface that the controls should inherit from, or is it good enough to just call the Send() function exposed on the controls?

Dynamic languages often encourage Duck Typing, in which methods of the object dictate how it should be used rather than an explicit contract (such as an interface).

This is the same for PHP; you don't really need interfaces. But they exist for architectural needs. In PHP, you can specify type hints for functions which can be useful.
Second, an interface is a contract. It's a formal contract that all objects from this interface have those functions. Better to ensure that your classes meet those requirements than to remember: "mm, this class has isEnabled() but the other one is checkIfEnabled()". Interfaces help you to standardise. Others working on the derived object don't have to check whether the name is isEnabled or checkIfEnabled (better to let the interpreter catch those problems).

Since you can call any method on any object in a dynamic language, I'm not sure how interfaces would come into play in any truly useful way. There are no contracts to enforce because everything is determined at invocation time - an object could even change whether it conforms to a "contract" through its life as methods are added and removed throughout runtime. The call will fail if the object doesn't fulfill a contract or it will fail if it doesn't implement a member - either case is the same for most practical purposes.

We saw a nice implementation in the page below, this is ours (short version of it)
var Interface = function (methods) {
var self = this;
self.methods = [];
for (var i = 0, len = methods.length; i < len; i++) {
self.methods.push(methods[i]);
}
this.implementedBy = function (object) {
for (var j = 0, methodsLen = self.methods.length; j < methodsLen; j++) {
var method = self.methods[j];
if (!object[method] || typeof object[method] !== 'function') {
return false;
}
}
return true;
}
};
//Call
var IWorkflow = new Interface(['start', 'getSteps', 'end']);
if (IWorkflow.implementedBy(currentWorkFlow)) {
currentWorkFlow.start(model);
}
The whole example is at:
http://www.javascriptbank.com/how-implement-interfaces-in-javascript.html

Another alternative to the interfaces is offered by bob.js:
1. Check if the interface is implemented:
var iFace = { say: function () { }, write: function () { } };
var obj1 = { say: function() { }, write: function () { }, read: function () { } };
var obj2 = { say: function () { }, read: function () { } };
console.log('1: ' + bob.obj.canExtractInterface(obj1, iFace));
console.log('2: ' + bob.obj.canExtractInterface(obj2, iFace));
// Output:
// 1: true
// 2: false
2. Extract interface from the object and still execute the functions properly:
var obj = {
msgCount: 0,
say: function (msg) { console.log(++this.msgCount + ': ' + msg); },
sum: function (a, b) { console.log(a + b); }
};
var iFace = { say: function () { } };
obj = bob.obj.extractInterface(obj, iFace);
obj.say('Hello!');
obj.say('How is your day?');
obj.say('Good bye!');
// Output:
// 1: Hello!
// 2: How is your day?
// 3: Good bye!

Related

Does the Factory Pattern in js violate the Open-Close principle?

since JS does not support abstract classes or inheritance, every time we want to add a new type to be created when using factory pattern, we will have to modify the code which mean we violate the open-close principle. for example, in the snapshot bellow - if we want to add a new employee type like Marketing, we will have to update the switch statement which is violation of the open-close principle. Is there any workaround to use the factory pattern without violation open-close principle?
function Accountant(){
console.log('I am accountant');
}
function Developer(){
console.log('I am developer');
}
function Sales(){
console.log('I am sales');
}
function CreateEmployee(employee){
switch(employee){
case('accountant'): return new Accountant();
case('developer'): return new Developer()
case('sales'): return new Sales();
}
}
if we want to add a new employee type, we will have to update the switch statement which is violation of the open-close principle.
No, it doesn't. The OCP is not about forbidding to update code. If we want to implement a new feature, we of course need to touch the code of the program. The OCP is about designing your interfaces so that your program can be easily extended without changing code all over the place - ideally you only have to provide the new code, and change the configuration of the program to make use of it - or if this is not configurable, change only the high-level building blocks.
I would argue that the factory pattern even facilitates application of the OCP - don't think about changes to the factory function, think about the modules that use it. Instead of changing all the code in all the modules that instantiates employee objects, all you need to do is to supply a different factory to them.
A step in the right direction is to create an employeeType object that holds the constructors:
const employeeType = {
Accountant,
Developer,
Salesperson
};
// console.log(new (employeeType["Accountant"])());
// Abstract away the hard-coded type above; the below randomization is strictly for demo purpose
const employeeTypeKeys = Object.keys(employeeType);
const employeeTypeIndex = Math.floor(employeeTypeKeys.length * Math.random());
console.log(new (employeeType[employeeTypeKeys[employeeTypeIndex]])());
function Accountant(){
console.log('I am an accountant');
}
function Developer(){
console.log('I am a developer');
}
function Salesperson(){
console.log('I am a salesperson');
}
I would argue the pattern isn't exactly something I'd like to extend but it's possible.
Say you have access to the CreateEmployee function alone and you'd want to extend it so you can also add Engineers.
import CreateEmployee from "./employee.js";
function Engineer(){
console.log("I'm an Engineer");
}
function CreateEmployeeAndEngineer(employeeType){
if(employeeType === 'Engineer') return new Engineer();
else {
return CreateEmployee(employeeType);
}
}
Simple (ehh... not really) function composition.
However, there's very little value for it in Javascript since it's untyped. Then of course functions, and therefore constructors, are first-class citizens and can be easily passed down to the new operator.
since JS does not support abstract classes or inheritance
Javascript does support inheritance through it's concept of prototype chain.
You could implement the Factory method pattern if you'd want.
If you want new instances to be created on the fly, you should use Object literals. Review the following design for an idea on how you may, or may not, want to go about this:
function ucFirst(string){
const s = string.split('');
return s.shift().toUpperCase()+s.join('');
}
function InstanceController(){
this.instances = [];
this.add = (name, obj)=>{
this.instances.push({name:name, obj:obj});
return this;
}
this.get = name=>{
for(let o of this.instances){
if(o.name === name){
return o.obj;
}
}
return false;
}
this.remove = name=>{
for(let i=0,a=this.instances,l=a.length; i<l; i++){
if(a[i].name === name){
a.splice(i, 1);
break;
}
}
return this;
}
}
const ic = new InstanceController;
const data1 = {
data:'could be from database',
more:'sure there can be more data',
numberTest: 2
}
const data2 = {test:'just a test'};
ic.add('developer', data1).add('accountant', {testing:'see'});
let dev = ic.get('developer'), aco = ic.get('accountant');
if(dev)console.log(dev);
if(aco)console.log(aco);
console.log(ic.get('nope'));
ic.remove('accountant'); aco = ic.get('accountant');
console.log(aco);

How to create javascript function constructor with default functionality and persistent properties?

I've got a slightly unusual pattern I'm trying to achieve and have not quite figured it out. My goal is to create a function called debugLog as a flexible console.log replacement, which can be called as follows:
debugLog('thing to log #1', 'thing to log #2', objectToLog1, objectToLog2);
^^ the number of params should be arbitrary, just as is possible with console.log
That is what I'll call the "default" functionality. Now I'd also like to add some additional functionality through property functions.
Examples:
debugLog.setDebugFlag(true); // sets the internal this.debugFlag property to true or false depending on param
I'm trying to do this in Node and what I have so far does not quite let me achieve this pattern:
var debugLog = function () {
this.debugFlag = this.debugFlag || true;
if (this.debugFlag) {
console.log.apply(null, arguments);
} else {
// production mode, nothing to log
}
};
debugLog.prototype.setDebugFlag = function (flagBool) {
this.debugFlag = flagBool;
}
module.exports = new debugLog();
This module would be including in a Node app using the standard require pattern:
var debugLog = require('./debugLog.js');
The question is how can I achieve this pattern of a function object with default functionality, but also extended "property" style functions? Please note I am already aware of the typical pattern where ALL functionality comes from function properties (such as debugLog.log() and debugLog.setDebugFlag()). But that patterns does NOT achieve my key goal of a shorthand for the default functionality that simply involves calling the function directly.
Is it even possible to do?
You could do it this way
var debugLog = (function() {
var debugFlag = true;
function log() {
if (debugFlag) {
console.log.apply(null, arguments);
} else {
// production mode, nothing to log
}
};
log.setDebugFlag = function(flag) {
debugFlag = flag;
}
return log;
})();
module.exports = debugLog;
You could use closure, like so:
// debugLog.js
var debugFlag = true;
function debugLog() {
if (debugFlag) {
console.log.apply(null, arguments);
} else {
// production mode, nothing to log
}
}
debugLog.setDebugFlag = function (newFlag) {
debugFlag = newFlag;
}
module.exports = debugLog;
and use it like this:
// otherFile.js
var debugLog = require('./debugLog');
debugLog('Hey!');
debugLog.setDebugFlag(false);
debugLog('This wont appear!');

How to choose OO design patterns for JavaScript

By OO I mean classical OO. I keep going back and forth between defining my "classes" ( javascript does not have traditional classes ) using the module pattern to provide privacy and using object literals to create a collection of "public statics".
I have no guiding force when I create "classes" that lets me determine what type of organization to use. Well, besides the fact that my code passes both jshint and jslint w/ no options set.
I'm working w/ about 1500 lines of code so I need a "guiding force" before the code becomes un-manageable and I have to scrap it.
I am well aware of the different ways to write "classes" in JavaScript. Those taught by JavaScript Web Applications written by Alex MacCaw as well as the numerous ways listed here on SO.
However, application wise, I just don't know what method to use.
The simplest seems to be a collection of methods and variables in an object literal like this:
var public_statics = {
public_func: function () {},
public_var: "hello"
}
and the most complicated seems to be - an IIFE.
(function(){
var private_var;
function private_func(){
}
})();
How do I know which one to use or the multitude of in-between variations?
For a concrete example: How about for a controller in the MVC.
Currently ( and some what randomly chosen), I implement a controller like this:
var Co = {};
Co.Controller = function(){
// 'classes' from Mo are called here
// 'classes' from Su are called here
}
then I tack on other Control related method to Co.
How do I choose what style of OO to use?
Updated
My library is currently divided between 4 namespaces:
var Mo = {},
Vi = {},
Co = {},
Su = {};
Model, View, and Controller should be self-explanatory and (Su)pport is for all "classes" not contained in the MVC, for example DOM access, Effects, Debug code, etc.
What OO style should I use to further organize this library/code?
Controller "Class" example:
/**
** Controller
*/
Co.Controller = function (o_p) {
var o_p_string_send;
Su.time();
o_p = Mo[o_p.model].pre(o_p);
if (o_p.result !== 'complete') {
o_p_string_send = JSON.stringify(o_p);
Su.time();
//Su.log(o_p_string_send);
Co.serverCall('pipe=' + o_p_string_send, function (o_p_string_receive) {
Su.time();
//Su.log(o_p_string_receive);
o_p.server = JSON.parse(o_p_string_receive);
Mo[o_p.model].post(o_p);
Su.time(true);
Su.log('Server time: [' + o_p.server.time + ']');
});
}
};
IFFEs are often confusing to read and personally, I have no idea why they have become so mainstream. I think code should be easy to read and concise. Attempting to simulate language behavior that is not part of the language specification is often-times a very dumb idea.
For example, JavaScript does not support multiple inheritance, polymorphism, or many other interesting paradigms. So a lot of times, we see people trying to create these crazy ways of sorta'-kinda' having polymorphism or private members, etc in JS. I think this is a mistake.
I'm currently working as a sort of hobby project on a high-performance JS data structures library (I'm trying to outperform Google's closure and a bunch of others). Coming from a C++ and Java background, I always like to make stuff classes and I like inheritance, etc, etc. Let me share some code-snippets with you. At first, I thought I was being clever because I was writing stuff like this:
function __namespace(n, v) {
return {"meta":{"namespace":n,"version":v}};
}
var FJSL = FJSL == undefined ? new __namespace("Fast JavaScript Library", 0.1) : FJSL;
__using = function(parent, child) {
clazz = new child();
clazz.super = new parent();
if (clazz.super == undefined) return clazz;
for (a in clazz.super) {
for (b in clazz) {
if (a == "constructor" || b == "constructor") continue;
if (clazz[b] === clazz.super[a]) continue;
if (a == b && typeof clazz[b] != typeof clazz.super[a]) throw "Typesafety breached on '" + a + "' while trying to resolve polymorphic properties.";
if (a == b && typeof clazz[b] == typeof clazz.super[a]) {
clazz["_"+a] = clazz.super[a];
} else if (clazz[a] == undefined) {
clazz[a] = clazz.super[a];
}
}
}
return clazz;
};
And I was using it like so (in the example of a simple Queue):
FJSL.Array = function() {
this.data = [];
this.contains = function(idx, element) {
for (var i = idx; i < this.data.length; i++) {
if (this.data[i] === element)
return i;
}
return -1;
}
this.size = function() {
return this.data.length;
}
}
FJSL.Queue = function() {
return __using(FJSL.Array,
function() {
this.head = 0;
this.tail = 0;
this.enqueue = function(element) {
this.data[this.tail++] = element;
};
this.dequeue = function() {
if (this.tail == this.head)
return undefined;
return this.data[this.head++];
};
this.peek = function() {
return this.data[this.head];
};
this.size = function() {
return this.tail - this.head;
};
this.contains = function(element) {
return this._contains(this.head, element);
};
}
)};
You'll note how I'm sort of faking inheritance (a Queue uses an Array, har har, I'm clever). However, this is absolutely insane to a) read and b) understand. I couldn't help but be reminded of this meme:
Let me show you functionally equivalent code without me trying to do all this fancy pre- and post-processing:
FJSL.Queue = function(opts) {
this.options = opts;
this.head = 0;
this.tail = 0;
this.data = [];
};
FJSL.Queue.prototype = {
add : function(element) {
this.data[this.tail++] = element;
},
enqueue : function(element) {
this.data[this.tail++] = element;
},
dequeue : function() {
if (this.tail == this.head) {
return undefined;
}
return this.data[this.head++];
},
peek : function() {
return this.data[this.head];
},
size : function() {
return this.tail - this.head;
},
contains : function(element) {
// XXX: for some reason a for : loop doesn't get JIT'ed in Chrome
for (var i = this.head; i < this.data.length; i++) {
if (this.data[i] === element) {
return true;
}
}
return false;
},
isEmpty : function() {
if (size) {
return true;
}
return false
},
clear : function() {
this.data = [];
}
};
Obviously, I'd have to duplicate the prototype constructor for any other structures that may use an array, but what I'm trying to accomplish is so much clearer, even a novice JS programmer can tell what's going on. Not only that, but if people want to modify the code, they know exactly where to go and what to do.
My suggestion is don't get caught up in the insanity of trying to make JS behave like C++ or Java. It's never going to. And yeah, you can fake inheritance and private/public/protected members, but JS was never intended for that. I think the repercussion of having this kind of bloated code (that attempts to simulate non-standard behavior) is very taxing on high-performance web-apps and their ilk.
In short, I suggest using an object literal:
var public_statics = {
public_func: function () {},
public_var: "hello"
}
It's easy to understand, easy to modify, and easy to extend. If your system is brittle enough to crash and burn if someone accidentally changes some "private" variable, you simply need to document it.
I personally prefer the IIFE simply because you can make methods private. Otherwise, you will have to do some sort of weird convention with underscores.
Furthermore, stylitically, if you encapsulate it within a function, you have the option of making semicolons - its plain old javascript. Requiring each line in the object literal to end with a comma seems funny to me.
Because JavaScript the language itself is implemented in many different ways, i.e. it is different for each browser, you already have to begin with inconsistency.
JavaScript does not directly support classical inheritance. ( It supports prototypical inheritance ).
For my needs I will choose not to implement classical inheritance. This is not ideal b.c. classical inheritance allows you to directly implement best practice OO - encapsulation, inheritance, and polymorphism.
However I prefer to wait until the language directly supports OO via classical inheritance or similar.
In the mean time I will just use the basic prototypical inheritance to help enable code re-use.

Does JavaScript have the interface type (such as Java's 'interface')?

I'm learning how to make OOP with JavaScript. Does it have the interface concept (such as Java's interface)?
So I would be able to create a listener...
There's no notion of "this class must have these functions" (that is, no interfaces per se), because:
JavaScript inheritance is based on objects, not classes. That's not a big deal until you realize:
JavaScript is an extremely dynamically typed language -- you can create an object with the proper methods, which would make it conform to the interface, and then undefine all the stuff that made it conform. It'd be so easy to subvert the type system -- even accidentally! -- that it wouldn't be worth it to try and make a type system in the first place.
Instead, JavaScript uses what's called duck typing. (If it walks like a duck, and quacks like a duck, as far as JS cares, it's a duck.) If your object has quack(), walk(), and fly() methods, code can use it wherever it expects an object that can walk, quack, and fly, without requiring the implementation of some "Duckable" interface. The interface is exactly the set of functions that the code uses (and the return values from those functions), and with duck typing, you get that for free.
Now, that's not to say your code won't fail halfway through, if you try to call some_dog.quack(); you'll get a TypeError. Frankly, if you're telling dogs to quack, you have slightly bigger problems; duck typing works best when you keep all your ducks in a row, so to speak, and aren't letting dogs and ducks mingle together unless you're treating them as generic animals. In other words, even though the interface is fluid, it's still there; it's often an error to pass a dog to code that expects it to quack and fly in the first place.
But if you're sure you're doing the right thing, you can work around the quacking-dog problem by testing for the existence of a particular method before trying to use it. Something like
if (typeof(someObject.quack) == "function")
{
// This thing can quack
}
So you can check for all the methods you can use before you use them. The syntax is kind of ugly, though. There's a slightly prettier way:
Object.prototype.can = function(methodName)
{
return ((typeof this[methodName]) == "function");
};
if (someObject.can("quack"))
{
someObject.quack();
}
This is standard JavaScript, so it should work in any JS interpreter worth using. It has the added benefit of reading like English.
For modern browsers (that is, pretty much any browser other than IE 6-8), there's even a way to keep the property from showing up in for...in:
Object.defineProperty(Object.prototype, 'can', {
enumerable: false,
value: function(method) {
return (typeof this[method] === 'function');
}
}
The problem is that IE7 objects don't have .defineProperty at all, and in IE8, it allegedly only works on host objects (that is, DOM elements and such). If compatibility is an issue, you can't use .defineProperty. (I won't even mention IE6, because it's rather irrelevant anymore outside of China.)
Another issue is that some coding styles like to assume that everyone writes bad code, and prohibit modifying Object.prototype in case someone wants to blindly use for...in. If you care about that, or are using (IMO broken) code that does, try a slightly different version:
function can(obj, methodName)
{
return ((typeof obj[methodName]) == "function");
}
if (can(someObject, "quack"))
{
someObject.quack();
}
Pick up a copy of 'JavaScript design patterns' by Dustin Diaz. There's a few chapters dedicated to implementing JavaScript interfaces through Duck Typing. It's a nice read as well. But no, there's no language native implementation of an interface, you have to Duck Type.
// example duck typing method
var hasMethods = function(obj /*, method list as strings */){
var i = 1, methodName;
while((methodName = arguments[i++])){
if(typeof obj[methodName] != 'function') {
return false;
}
}
return true;
}
// in your code
if(hasMethods(obj, 'quak', 'flapWings','waggle')) {
// IT'S A DUCK, do your duck thang
}
JavaScript (ECMAScript edition 3) has an implements reserved word saved up for future use. I think this is intended exactly for this purpose, however, in a rush to get the specification out the door they didn't have time to define what to do with it, so, at the present time, browsers don't do anything besides let it sit there and occasionally complain if you try to use it for something.
It is possible and indeed easy enough to create your own Object.implement(Interface) method with logic that baulks whenever a particular set of properties/functions are not implemented in a given object.
I wrote an article on object-orientation where use my own notation as follows:
// Create a 'Dog' class that inherits from 'Animal'
// and implements the 'Mammal' interface
var Dog = Object.extend(Animal, {
constructor: function(name) {
Dog.superClass.call(this, name);
},
bark: function() {
alert('woof');
}
}).implement(Mammal);
There are many ways to skin this particular cat, but this is the logic I used for my own Interface implementation. I find I prefer this approach, and it is easy to read and use (as you can see above). It does mean adding an 'implement' method to Function.prototype which some people may have a problem with, but I find it works beautifully.
Function.prototype.implement = function() {
// Loop through each interface passed in and then check
// that its members are implemented in the context object (this).
for(var i = 0; i < arguments.length; i++) {
// .. Check member's logic ..
}
// Remember to return the class being tested
return this;
}
JavaScript Interfaces:
Though JavaScript does not have the interface type, it is often times needed. For reasons relating to JavaScript's dynamic nature and use of Prototypical-Inheritance, it is difficult to ensure consistent interfaces across classes -- however, it is possible to do so; and frequently emulated.
At this point, there are handfuls of particular ways to emulate Interfaces in JavaScript; variance on approaches usually satisfies some needs, while others are left unaddressed. Often times, the most robust approach is overly cumbersome and stymies the implementor (developer).
Here is an approach to Interfaces / Abstract Classes that is not very cumbersome, is explicative, keeps implementations inside of Abstractions to a minimum, and leaves enough room for dynamic or custom methodologies:
function resolvePrecept(interfaceName) {
var interfaceName = interfaceName;
return function curry(value) {
/* throw new Error(interfaceName + ' requires an implementation for ...'); */
console.warn('%s requires an implementation for ...', interfaceName);
return value;
};
}
var iAbstractClass = function AbstractClass() {
var defaultTo = resolvePrecept('iAbstractClass');
this.datum1 = this.datum1 || defaultTo(new Number());
this.datum2 = this.datum2 || defaultTo(new String());
this.method1 = this.method1 || defaultTo(new Function('return new Boolean();'));
this.method2 = this.method2 || defaultTo(new Function('return new Object();'));
};
var ConcreteImplementation = function ConcreteImplementation() {
this.datum1 = 1;
this.datum2 = 'str';
this.method1 = function method1() {
return true;
};
this.method2 = function method2() {
return {};
};
//Applies Interface (Implement iAbstractClass Interface)
iAbstractClass.apply(this); // .call / .apply after precept definitions
};
Participants
Precept Resolver
The resolvePrecept function is a utility & helper function to use inside of your Abstract Class. Its job is to allow for customized implementation-handling of encapsulated Precepts (data & behavior). It can throw errors or warn -- AND -- assign a default value to the Implementor class.
iAbstractClass
The iAbstractClass defines the interface to be used. Its approach entails a tacit agreement with its Implementor class. This interface assigns each precept to the same exact precept namespace -- OR -- to whatever the Precept Resolver function returns. However, the tacit agreement resolves to a context -- a provision of Implementor.
Implementor
The Implementor simply 'agrees' with an Interface (iAbstractClass in this case) and applies it by the use of Constructor-Hijacking: iAbstractClass.apply(this). By defining the data & behavior above, and then hijacking the Interface's constructor -- passing Implementor's context to the Interface constructor -- we can ensure that Implementor's overrides will be added, and that Interface will explicate warnings and default values.
This is a very non-cumbersome approach which has served my team & I very well for the course of time and different projects. However, it does have some caveats & drawbacks.
Drawbacks
Though this helps implement consistency throughout your software to a significant degree, it does not implement true interfaces -- but emulates them. Though definitions, defaults, and warnings or errors are explicated, the explication of use is enforced & asserted by the developer (as with much of JavaScript development).
This is seemingly the best approach to "Interfaces in JavaScript", however, I would love to see the following resolved:
Assertions of return types
Assertions of signatures
Freeze objects from delete actions
Assertions of anything else prevalent or needed in the specificity of the JavaScript community
That said, I hope this helps you as much as it has my team and I.
Hope, that anyone who's still looking for an answer finds it helpful.
You can try out using a Proxy (It's standard since ECMAScript 2015): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
latLngLiteral = new Proxy({},{
set: function(obj, prop, val) {
//only these two properties can be set
if(['lng','lat'].indexOf(prop) == -1) {
throw new ReferenceError('Key must be "lat" or "lng"!');
}
//the dec format only accepts numbers
if(typeof val !== 'number') {
throw new TypeError('Value must be numeric');
}
//latitude is in range between 0 and 90
if(prop == 'lat' && !(0 < val && val < 90)) {
throw new RangeError('Position is out of range!');
}
//longitude is in range between 0 and 180
else if(prop == 'lng' && !(0 < val && val < 180)) {
throw new RangeError('Position is out of range!');
}
obj[prop] = val;
return true;
}
});
Then you can easily say:
myMap = {}
myMap.position = latLngLiteral;
If you want to check via instanceof (asked by #Kamaffeather), you can wrap it in an object like so:
class LatLngLiteral {
constructor(props)
{
this.proxy = new Proxy(this, {
set: function(obj, prop, val) {
//only these two properties can be set
if(['lng','lat'].indexOf(prop) == -1) {
throw new ReferenceError('Key must be "lat" or "lng"!');
}
//the dec format only accepts numbers
if(typeof val !== 'number') {
throw new TypeError('Value must be numeric');
}
//latitude is in range between 0 and 90
if(prop == 'lat' && !(0 < val && val < 90)) {
throw new RangeError('Position is out of range!');
}
//longitude is in range between 0 and 180
else if(prop == 'lng' && !(0 < val && val < 180)) {
throw new RangeError('Position is out of range!');
}
obj[prop] = val;
return true;
}
})
return this.proxy
}
}
This can be done without using Proxy but instead the classes getters and setters:
class LatLngLiteral {
#latitude;
#longitude;
get lat()
{
return this.#latitude;
}
get lng()
{
return this.#longitude;
}
set lat(val)
{
//the dec format only accepts numbers
if(typeof val !== 'number') {
throw new TypeError('Value must be numeric');
}
//latitude is in range between 0 and 90
if(!(0 < val && val < 90)) {
throw new RangeError('Position is out of range!');
}
this.#latitude = val
}
set lng(val)
{
//the dec format only accepts numbers
if(typeof val !== 'number') {
throw new TypeError('Value must be numeric');
}
//longitude is in range between 0 and 180
if(!(0 < val && val < 180)) {
throw new RangeError('Position is out of range!');
}
this.#longitude = val
}
}
abstract interface like this
const MyInterface = {
serialize: () => {throw "must implement serialize for MyInterface types"},
print: () => console.log(this.serialize())
}
create an instance:
function MyType() {
this.serialize = () => "serialized "
}
MyType.prototype = MyInterface
and use it
let x = new MyType()
x.print()
You need interfaces in Java since it is statically typed and the contract between classes should be known during compilation. In JavaScript it is different. JavaScript is dynamically typed; it means that when you get the object you can just check if it has a specific method and call it.
When you want to use a transcompiler, then you could give TypeScript a try. It supports draft ECMA features (in the proposal, interfaces are called "protocols") similar to what languages like coffeescript or babel do.
In TypeScript your interface can look like:
interface IMyInterface {
id: number; // TypeScript types are lowercase
name: string;
callback: (key: string; value: any; array: string[]) => void;
type: "test" | "notATest"; // so called "union type"
}
What you can't do:
Define RegExp patterns for type value
Define validation like string length
Number ranges
etc.
there is no native interfaces in JavaScript,
there are several ways to simulate an interface. i have written a package that does it
you can see the implantation here
Try this: Describe the interface as a class and use #implements JSDoc to show that a given class implements the interface defined. You'll see red squiggly lines on the class name if its not implementing some properties. I tested with VSCode.
// #ts-check
// describe interface using a class
class PlainInterface {
size = 4;
describe() {}
show(){ }
}
/**
* #implements PlainInterface
*/
class ConcretePlain {
size = 4;
describe() {
console.log('I am described')
}
show(){
console.log('I am shown')
}
}
const conc = new ConcretePlain();
conc.describe();
Javascript does not have interfaces. But it can be duck-typed, an example can be found here:
http://reinsbrain.blogspot.com/2008/10/interface-in-javascript.html
This is an old question, nevertheless this topic never ceases to bug me.
As many of the answers here and across the web focus on "enforcing" the interface, I'd like to suggest an alternative view:
I feel the lack of interfaces the most when I'm using multiple classes that behave similarly (i.e. implement an interface).
For example, I have an Email Generator that expects to receive Email Sections Factories, that "know" how to generate the sections' content and HTML. Hence, they all need to have some sort of getContent(id) and getHtml(content) methods.
The closest pattern to interfaces (albeit it's still a workaround) I could think of is using a class that'll get 2 arguments, which will define the 2 interface methods.
The main challenge with this pattern is that the methods either have to be static, or to get as argument the instance itself, in order to access its properties. However there are cases in which I find this trade-off worth the hassle.
class Filterable {
constructor(data, { filter, toString }) {
this.data = data;
this.filter = filter;
this.toString = toString;
// You can also enforce here an Iterable interface, for example,
// which feels much more natural than having an external check
}
}
const evenNumbersList = new Filterable(
[1, 2, 3, 4, 5, 6], {
filter: (lst) => {
const evenElements = lst.data.filter(x => x % 2 === 0);
lst.data = evenElements;
},
toString: lst => `< ${lst.data.toString()} >`,
}
);
console.log('The whole list: ', evenNumbersList.toString(evenNumbersList));
evenNumbersList.filter(evenNumbersList);
console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
With an interface you can implement a way of polymorphism. Javascript does NOT need the interface type to handle this and other interface stuff. Why? Javascript is a dynamically typed language. Take as example an array of classes that have the same methods:
Circle()
Square()
Triangle()
If you want to know how polymorphism works the Book MFC of David Kruglinsky is great (written for C++)
Implement in those classes the method draw() push the instances of those classes in the array and call the draw() methods in a loop that iterates the array. That's completely valid. You could say you implemented implicitly an abstract class. Its not there in reality but in your mind you did it and Javascript has no problem with it. The difference with an real interface is that you HAVE to implement all the interface methods and that's in this case not needed.
An interface is a contract. You will have to implement all the methods. Only by making it statically you have to do that.
Its questionable to change a language like Javascript from dynamic to static. Its not mend to be static. Experienced developers have no problems with the dynamic nature of Javascript.
So the reason to use Typescript are not clear to me. If you use NodeJS together with Javascript you can build extremely efficient and cost effective enterprise websites. The Javascript/NodeJS/MongoDB combination are already great winners.
I know this is an old one, but I've recently found myself needing more and more to have a handy API for checking objects against interfaces. So I wrote this: https://github.com/tomhicks/methodical
It's also available via NPM: npm install methodical
It basically does everything suggested above, with some options for being a bit more strict, and all without having to do loads of if (typeof x.method === 'function') boilerplate.
Hopefully someone finds it useful.
This is old but I implemented interfaces to use on ES6 without transpiller.
https://github.com/jkutianski/ES6-Interfaces
It bugged me too to find a solution to mimic interfaces with the lower impacts possible.
One solution could be to make a tool :
/**
#parameter {Array|object} required : method name list or members types by their name
#constructor
*/
let Interface=function(required){
this.obj=0;
if(required instanceof Array){
this.obj={};
required.forEach(r=>this.obj[r]='function');
}else if(typeof(required)==='object'){
this.obj=required;
}else {
throw('Interface invalid parameter required = '+required);
}
};
/** check constructor instance
#parameter {object} scope : instance to check.
#parameter {boolean} [strict] : if true -> throw an error if errors ar found.
#constructor
*/
Interface.prototype.check=function(scope,strict){
let err=[],type,res={};
for(let k in this.obj){
type=typeof(scope[k]);
if(type!==this.obj[k]){
err.push({
key:k,
type:this.obj[k],
inputType:type,
msg:type==='undefined'?'missing element':'bad element type "'+type+'"'
});
}
}
res.success=!err.length;
if(err.length){
res.msg='Class bad structure :';
res.errors=err;
if(strict){
let stk = new Error().stack.split('\n');
stk.shift();
throw(['',res.msg,
res.errors.map(e=>'- {'+e.type+'} '+e.key+' : '+e.msg).join('\n'),
'','at :\n\t'+stk.join('\n\t')
].join('\n'));
}
}
return res;
};
Exemple of use :
// create interface tool
let dataInterface=new Interface(['toData','fromData']);
// abstract constructor
let AbstractData=function(){
dataInterface.check(this,1);// check extended element
};
// extended constructor
let DataXY=function(){
AbstractData.apply(this,[]);
this.xy=[0,0];
};
DataXY.prototype.toData=function(){
return [this.xy[0],this.xy[1]];
};
// should throw an error because 'fromData' is missing
let dx=new DataXY();
With classes
class AbstractData{
constructor(){
dataInterface.check(this,1);
}
}
class DataXY extends AbstractData{
constructor(){
super();
this.xy=[0,0];
}
toData(){
return [this.xy[0],this.xy[1]];
}
}
It's still a bit performance consumming and require dependancy to the Interface class, but can be of use for debug or open api.
Js doesn't have interfaces but typescript does!
While there isn't a interface in javaScript as there is in Java you could mimic the behaviour a bit with the code under this message. because an interface is basicly an enforced contract you could build it yourself.
The code below exists out of 3 classes an interface, parent and child class.
The Interface has the methods to check if the methods and properties exist required exist.
The Parent is used to enforce the required methods and properties in the child using the Interface class.
The Child is the class that the parents rules are enforced on.
After you set it up correctly you will see an error in the console if a method or property is missing in the child and nothing if the child implements the contract correctly.
class Interface {
checkRequiredMethods(methodNames) {
setTimeout( () => {
const loopLength = methodNames.length;
let i = 0
for (i; i<loopLength; i++) {
if (typeof this[methodNames[i]] === "undefined") {
this.throwMissingMethod(methodNames[i]);
}
else if (typeof this[methodNames[i]] !== "function") {
this.throwNotAMethod(methodNames[i]);
}
}
}, 0);
}
checkRequiredProperties(propNames) {
setTimeout( () => {
const loopLength = propNames.length;
let i = 0
for (i; i<loopLength; i++) {
if (typeof this[propNames[i]] === "undefined") {
this.throwMissingProperty(propNames[i]);
}
else if (typeof this[propNames[i]] === "function") {
this.throwPropertyIsMethod(propNames[i]);
}
}
}, 0);
}
throwMissingMethod(methodName) {
throw new Error(`error method ${methodName} is undefined`);
}
throwNotAMethod(methodName) {
throw new Error(`error method ${methodName} is not a method`);
}
throwMissingProperty(propName) {
throw new Error(`error property ${propName} is not defined`);
}
throwPropertyIsMethod(propName) {
throw new Error(`error property ${propName} is a method`);
}
}
class Parent extends Interface {
constructor() {
super()
this.checkRequiredProperties([
"p1",
"p2",
"p3",
"p4",
"p5"
]);
this.checkRequiredMethods([
"m1",
"m2",
"m3",
"m4"
]);
}
}
class Child extends Parent {
p1 = 0;
p2 = "";
p3 = false;
p4 = [];
p5 = {};
constructor() {
super();
}
m1() {}
m2() {}
m3() {}
m4() {}
}
new Child()
No, but it has mixins.
You can use Abstract sub-classss or mixins as an alternative https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#mix-ins

JavaScript getter for all properties

Long story short: I'm in a situation where I'd like a PHP-style getter, but in JavaScript.
My JavaScript is running in Firefox only, so Mozilla specific JS is OK by me.
The only way I can find to make a JS getter requires specifying its name, but I'd like to define a getter for all possible names. I'm not sure if this is possible, but I'd very much like to know.
Proxy can do it! I'm so happy this exists!! An answer is given here: Is there a javascript equivalent of python's __getattr__ method? . To rephrase in my own words:
var x = new Proxy({}, {
get(target, name) {
return "Its hilarious you think I have " + name
}
})
console.log(x.hair) // logs: "Its hilarious you think I have hair"
Proxy for the win! Check out the MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Works in chrome, firefox, and node.js. Downsides: doesn't work in IE - freakin IE. Soon.
You can combine proxy and class to have a nice looking code like php:
class Magic {
constructor () {
return new Proxy(this, this);
}
get (target, prop) {
return this[prop] || 'MAGIC';
}
}
this binds to the handler, so you can use this instead of target.
Note: unlike PHP, proxy handles all prop access.
let magic = new Magic();
magic.foo = 'NOT MAGIC';
console.log(magic.foo); // NOT MAGIC
console.log(magic.bar); // MAGIC
You can check which browsers support proxy http://caniuse.com/#feat=proxy.
The closest you can find is __noSuchMethod__ (__noSuchMethod__ is deprecated), which is JavaScript's equivalent of PHP's __call().
Unfortunately, there's no equivalent of __get/__set, which is a shame, because with them we could have implemented __noSuchMethod__, but I don't yet see a way to implement properties (as in C#) using __noSuchMethod__.
var foo = {
__noSuchMethod__ : function(id, args) {
alert(id);
alert(args);
}
};
foo.bar(1, 2);
Javascript 1.5 does have getter/setter syntactic sugar. It's explained very well by John Resig here
It's not generic enough for web use, but certainly Firefox has them (also Rhino, if you ever want to use it on the server side).
If you really need an implementation that works, you could "cheat" your way arround by testing the second parameter against undefined, this also means you could use get to actually set parameter.
var foo = {
args: {},
__noSuchMethod__ : function(id, args) {
if(args === undefined) {
return this.args[id] === undefined ? this[id] : this.args[id]
}
if(this[id] === undefined) {
this.args[id] = args;
} else {
this[id] = args;
}
}
};
If you're looking for something like PHP's __get() function, I don't think Javascript provides any such construct.
The best I can think of doing is looping through the object's non-function members and then creating a corresponding "getXYZ()" function for each.
In dodgy pseudo-ish code:
for (o in this) {
if (this.hasOwnProperty(o)) {
this['get_' + o] = function() {
// return this.o -- but you'll need to create a closure to
// keep the correct reference to "o"
};
}
}
I ended up using a nickfs' answer to construct my own solution. My solution will automatically create get_{propname} and set_{propname} functions for all properties. It does check if the function already exists before adding them. This allows you to override the default get or set method with our own implementation without the risk of it getting overwritten.
for (o in this) {
if (this.hasOwnProperty(o)) {
var creategetter = (typeof this['get_' + o] !== 'function');
var createsetter = (typeof this['set_' + o] !== 'function');
(function () {
var propname = o;
if (creategetter) {
self['get_' + propname] = function () {
return self[propname];
};
}
if (createsetter) {
self['set_' + propname] = function (val) {
self[propname] = val;
};
}
})();
}
}
This is not exactly an answer to the original question, however this and this questions are closed and redirect here, so here I am. I hope I can help some other JS newbie that lands here as I did.
Coming from Python, what I was looking for was an equivalent of obj.__getattr__(key)and obj.__hasattr__(key) methods. What I ended up using is:
obj[key] for getattr and obj.hasOwnProperty(key) for hasattr (doc).
It is possible to get a similar result simply by wrapping the object in a getter function:
const getProp = (key) => {
const dictionary = {
firstName: 'John',
lastName: 'Doe',
age: 42,
DEFAULT: 'there is no prop like this'
}
return (typeof dictionary[key] === 'undefined' ? dictionary.DEFAULT : dictionary[key]);
}
console.log(getProp('age')) // 42
console.log(getProp('Hello World')) // 'there is no prop like this'

Categories