简体   繁体   English

JavaScript原型组织

[英]Javascript prototype organisation

With this organisation, is it possible to reference the "id" property? 通过该组织,是否可以引用“ id”属性?

  function house(id) {  this.id = id }

  house.prototype.buy  = function() {  }
  house.prototype.sell = function() {  }

  house.prototype.buy.makeOffer=function(){
    //how can id be printed?
    console.log( 'id = ' + this.????  )      
  }

  var h = new house(1)
  h.buy.makeOffer();

I am trying to figure out the best way to organize a lot of prototypes for an object. 我试图找出最好的方法来组织一个对象的许多原型。 As .buy will have a lot of sub-function an so will .sell() ie: 由于.buy将具有很多子功能,因此.sell()也将具有以下子功能:

  h.buy.makeOffer();
  h.buy.inspect();
  h.buy.counterOffer();
  h.buy.signContact();

  h.sell.prepare()
  h.sell.advertise()
  h.sell.reviewOffer()

It's really not very easy to use a structure like this in Javascript: 在Javascript中使用这样的结构真的不是很容易:

house.prototype.buy.makeOffer=function(){
    //how can id be printed?
    console.log( 'id = ' + this.????  )      
}

The issue is that when you call that method on an instance of house like this: 问题是,当您像这样在house实例上调用该方法时:

var h = new house(1);
h.buy.makeOffer();

the this value in the makeOffer() method will point to the buy object in the prototype (which is your buy method) and it will NOT point to your house object. makeOffer()方法中的this值将指向原型中的buy对象(这是您的buy方法),而不会指向您的house对象。 That's just how method calls work in Javascript ( this points to the object which had the method) which renders these nested methods when there's actual instance data that you want to reference via this very impractical. 这就是方法调用在Javascript中的工作方式( this指向具有该方法的对象),当您希望通过this非常不实际的方式引用实际的实例数据时,该方法将呈现这些嵌套的方法。


The usual solution is to not implement the nesting. 通常的解决方案是不实现嵌套。 Just integrate the names without an extra layer of objects like this: 只需集成名称,无需像这样添加额外的对象层:

house.prototype.buyMakeOffer=function(){
    //how can id be printed?
    console.log( 'id = ' + this.????  )      
}

var h = new house(1);
h.buyMakeOffer();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM