Lime
Lime

Reputation: 13569

Javascript This Change Value

How could I correct this behavior so this inside is.green refers to the new book(). Because I'm convinced there isn't a way.

function book(){}
book.prototype.is = function(){};

book.prototype.is.green = function(){
  alert(this);
  // this should refer to 'new book' not  `is` function
  return this;
};

var Book = new book();

Book.is.green();

TLDR

Is there a way to construct an new prototype object for each new book that could hold the correct reference? Are there any other potential techniques?

No wrapper functions/altering the book function

Upvotes: 1

Views: 1005

Answers (2)

user578895
user578895

Reputation:

book.prototype.is = function(){ return this; }
Book.is().green();

or (I know you said you didn't want to alter the constructor, but):

function book(){ this.is = this; }
Book.is.green();

or (non-cross-browser):

book.prototype = {
    get is(){ return this; }
};
Book.is.green();

What's the point of this? Just to have the word "is" needlessly placed somewhere? What's wrong with Book.isGreen()?

Upvotes: 3

Jamie Dixon
Jamie Dixon

Reputation: 53991

I think if you have each method on your object return the base object then this will be what you want.

A bit like how jQuery methods always return a reference to the jQuery object.

Upvotes: 0

Related Questions