i am trying to use my parent function to have a value. this is probably silly question but I haven't been able to find a straight to point tutorial on how to do it.
I know that while using prototype it is possible to
function handler (selector) {
return selector;
}
Object.prototype.alertLine = function () {
alert(this);}
handler('hello').alertLine();
and still receive an alert. but i want to know if there is a way to specify the object,sting,number in the parent function eg
function handler(selector) {
if (typeof(selector) == 'string'){
return String(selector);
}
if (typeof(selector) == 'number') {
return Number(selector);
}
if (typeof (selector) == 'object') {
return Object(selector);
}
}
handler.prototype.alertLine = function () {
alert(this);
}
handler('hello').alertLine();
I don't mind if Handler is an object or not it only matters if i am pass values using this method.
thank you in advance.
2 Answers 2
If you want to do something like that you need to instantiate an object of handler, not user it as a method. You want a function constructor.
function Handler(selector){
if (typeof(selector) == 'string'){
this.selector = String(selector);
}
if (typeof(selector) == 'number') {
this.selector = Number(selector);
}
if (typeof (selector) == 'object') {
this.selector = Object(selector);
}
}
Handler.prototype.alertLine = function(){
alert(this.selector);
}
var h = new Handler("hello");
h.alertLine();
Comments
"The idea is for the person to reinitialize a new object every time in one line of code so instead of var a = new Handler('hello'); a.alertLine(); instead of this I want to change to this var a = new Handler; then reference to a new parameter each time a('hello').alertLine()"
I'm not really sure why you want to do it like that but something like this may help you:
var Handler = function() {
var fun = function() {}
fun.prototype.set = function(t) {this.t = t; return this;}
fun.prototype.alertLine = function(){ alert(this.t); }
return new fun;
}
var a = Handler();
a.set('foo').alertLine();
Comments
Explore related questions
See similar questions with these tags.