I’m trying to create a new class, but it doesn’t seem to be working. Here’s the code:
<script>
var myClass = function(arg){
return new init(arg);
}
var init = function(arg){
return arg;
}
init.prototype.prop = true;
</script>
The problem is that myClass('foo') doesn’t return 'foo' as expected. Instead, it returns init.
Then I tried this code:
var init = function(arg){
return [arg];//Now init returns an array
}
The myClass('foo') returns ['foo'], but then myClass('foo').prop turns into undefined. Does anyone know how to solve it?
EDIT: I want to create this class more or less as jQuery does.
For example: $('div') returns directly a value (in case, all div tags), but not an object with a property that stores this values
When you call
new init()and withininit()you return a non-object, it yields an instance ofinitinstead of the returned value.If you return an Array from your
init()function, it gets returned instead; but Array doesn’t take yourinitprototype into consideration 🙂See also: https://stackoverflow.com/a/1978474/1338292
If you want to be like an array, you can do this:
It makes
initinherit from theArrayprototype (i.e.[]). After that you can add more properties and methods to theinitprototype as you wish.