I am new to javascript app development.When i came with functions and all i have found a code like
function Parenizor(value) {
console.log(this.setValue());
}
Parenizor.method('setValue', function () {
console.log('am called');
});
Parenizor.method('getValue', function () {
return 1;
});
Parenizor.method('toString', function () {
return 2;
});
And when i called the function like
var a = new Parenizor(1)
a.setValue()
It throws me error like Undefined not a function
..Why is it like this ??..Hope anyone here can find my mistake ..Thanz ..:)
That's not how you define a method. Do it like this:
function K() {}
K.prototype.setValue = function () {};
K.prototype.getValue = function () {};
It seems your code comes from Classical Inheritance in JavaScript , by Douglas Crockford.
I guess you didn't read this part:
To make the examples above work, I wrote four sugar methods. First, the
method
method, which adds an instance method to a class.Function.prototype.method = function (name, func) { this.prototype[name] = func; return this; };
Javascript is OO, not with classes, but with prototypes. First when you declare Parenizor, you're declaring a 'constructor'. You probaly want this:
function Parenizor(){
var value = null;
this.setValue = function(val){
value = val;
};
this.getValue = function(){
return value;
};
this.toString = function(){
return String(value);
};
}
Or also, setting into the object prototype:
function Parenizor(){}
Parenizor.prototype._value = null;
Parenizor.prototype.setValue = function(){...};
Parenizor.prototype.getValue = function(){...};
Parenizor.prototype.toString = function(){...};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.