Jitender
Jitender

Reputation: 7971

How to inherit Class in javascript?

The function is not working, It is not putting values in "input".

function example(id){
    this.code= function(){$('.'+id).val(id)}
    this.validate= function (){
        $('.'+id).keyup(function (e){
            if(e.keyCode==13) this.code();
        })
    }
}

body

<input type="text" class="test"/>
<input type="text" class="test1"/>
<script type="text/javascript">
    var test= new example('test')
    var test1= new example('test1')
    test.validate()
    test1.validate()
</script>

Upvotes: 1

Views: 97

Answers (2)

Peter
Peter

Reputation: 38455

Well javascript is a bit hard to understand when it comes to this..

this article explains some of it http://www.crockford.com/javascript/inheritance.html But one way to solve it would be

function example(id){
    this.code= function(){$('.'+id).val(id)}
    var self = this;
    this.validate= function (){
        $('.'+id).keyup(function (e){
            if(e.keyCode==13) self.code();
        });
    }
}

Upvotes: 1

Louis Ricci
Louis Ricci

Reputation: 21086

Your keyup event handler will have a different "this". You can use bind to correct the problem

keyup(function (e){
if(e.keyCode==13) this.code();
}.bind(this))

When you bind to an event, the handler is called with the "this" keyword set to the object that fired the event, not the object that created the event.

Upvotes: 4

Related Questions