Skip to content

Instantly share code, notes, and snippets.

@dennissterzenbach
Created August 29, 2017 10:42
Show Gist options
  • Save dennissterzenbach/135d1eba0cb736dc241eca0a7e3f3dda to your computer and use it in GitHub Desktop.
Save dennissterzenbach/135d1eba0cb736dc241eca0a7e3f3dda to your computer and use it in GitHub Desktop.
check if given argument is ES6 class or ES5 function based class-like
// we can determine whether a given
// function based implementation of a "class" has "writable" attribute set to true.
// ES6 class based implementation has "writable" attribute set to false.
//
// Given any object: it does not matter if it was made from a function or a class,
// there always is the constructor and based on this we get to the same results
// like testing on the function/class itself.
//
// So simply give the isClassBasedFunction any instance or function/class and
// it will tell you if it was made from a ES6 class or not.
function isClassBased(theClassToTest) {
theClassToTest = (typeof theClassToTest === 'object') && ('constructor' in theClassToTest) && theClassToTest.constructor || theClassToTest;
return !Object.getOwnPropertyDescriptor(theClassToTest, 'prototype').writable;
}
// These are some tests run to make sure the isClassBased function works correctly
class ClassBasedClass {
test() {
console.log('INST C');
}
static test2() {
console.log('STATIC C');
}
}
function FunctionBasedClass() {
this.test = function() {
console.log('INST F');
}
}
FunctionBasedClass.test2 = function() {
console.log('STATIC F');
}
var instanceToTest = new FunctionBasedClass();
var instance2ToTest = new ClassBasedClass();
var toTest = [
instanceToTest,
FunctionBasedClass,
instance2ToTest,
ClassBasedClass
];
toTest.map(isClassBased);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment