简体   繁体   English

Crockford关于构造函数调用模式的代码

[英]Crockford's code concerning the Constructor Invocation Pattern

The below code is almost identical to some code from Douglas Crockford's superb book JavaScript: The Good Parts, from pages 29-30. 下面的代码几乎与Douglas Crockford的精湛书籍JavaScript:The Good Parts,第29-30页中的一些代码完全相同。 The only difference is that he adds the get_status property like so: 唯一的区别是他添加了get_status属性,如下所示:

Quo.prototype.get_status=function() {
  this.status=string;
}

My question is why his code runs OK but my little change, below, results in an error that says myQuo has no get_status method? 我的问题是为什么他的代码运行正常,但我的小改动,下面,导致一个错误,说myQuo没有get_status方法?

<script>
  var Quo=function(string) {
    this.status=string;
  }
  Quo.get_status=function() {
    return this.status;
  }
  var myQuo=new Quo("confused");
  alert(myQuo.get_status());
</script>

You're adding the method to the Quo function object, not to its prototype, so it will not be inherited by instances created with new Quo() . 您将方法添加到Quo函数对象,而不是其原型,因此它不会被使用new Quo()创建的实例继承。 A function added in this way is a bit like a static method in classic OOP languages - it can be called with Quo.get_status() , but it won't be inherited by instances and this will refer to the Quo function itself. 以这种方式添加的函数有点像经典OOP语言中的静态方法 - 可以使用Quo.get_status()调用它,但它不会被实例继承, this将引用Quo函数本身。

Quo.status = "foo";
Quo.get_status(); // "foo"

Functions are objects in JavaScript. 函数是JavaScript中的对象。 When you add properties to functions then they are not inherited by the instances of that function. 向函数添加属性时,它们不会被该函数的实例继承。 However when you add properties to the prototype of the function then they are inherited. 但是,当您向函数原型添加属性时,它们将被继承。 To understand how prototype-based inheritance works in JavaScript read the following answer . 要了解基于原型的继承如何在JavaScript中工作,请阅读以下答案

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

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