-1

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

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

"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(); 

http://jsfiddle.net/herostwist/yPSpT/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.