Ensuring type when Duck Typing in Javascript a.k.a. Duck Checking
In Javascript there is no such thing as an interface, at least not yet, but sometimes it can be really useful to know if an object is similar to another, i.e. checking if object A implements all methods in object B, to ensure nothing goes wrong when Duck Typing.
Therefor I've written this nifty little method which does this kind of typechecking:
Object.prototype.doesImplement = function (interfaceObj) {
for (var key in interfaceObj) {
if (interfaceObj.hasOwnProperty(key) && typeof this[key] !== typeof interfaceObj[key]) {
return false;
}
}
return true;
};
The doesImplement
method can then be used like this:
/* Interfaces */
var IRunnable = {
run: function () {}
},
IUser = {
username: '',
};
var myRunnable = {
run: function () {
alert("I'm running!");
}
};
var myUser = {username: 'user1'};
console.log(myRunnable.doesImplement(IRunnable)); /* true */
console.log(myRunnable.doesImplement(IUser)); /* false */
console.log(myUser.doesImplement(IUser)); /* true */
console.log(myUser.doesImplement(IRunnable)); /* false */
I hope you can find it useful!
Written by Joakim Bengtson
Related protips
3 Responses
Thanks! Better now? :)
over 1 year ago
·
I think your code could be useful in a handful of situations. But I think you should consider reading about why is not a good practice to extend Object:
over 1 year ago
·
I totally agree with you! Why I did indeed extend Object in this case was for the nice resulting syntax ;)
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Related Tags
#javascript
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#