开发者

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/alteri开发者_如何学编程ng the book function


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()?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜