简体   繁体   English

Javascript原型继承不会调用预期的方法

[英]Javascript prototype inheritance doesn't call expected method

Why does this print out 'bye' instead of 'hello'? 为什么打印出“再见”而不是“你好”? According to the inheritance chain as is described in this blog post, I would've thought it would log 'hello'. 根据博客文章中描述的继承链,我认为它会记录'hello'。

http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/ http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/

class Test {
  hello() {
    console.log('hello')
  }
}

Test.prototype.hello = function(){
  console.log('bye')
}

const t = new Test
t.hello()

You are rewriting the definition of hello on the "prototype". 您正在重写“原型”上的hello定义。 When you do class Test () ... hello is the equivalent of 当你上课时Test()......你好相当于

Test.prototype.hello Test.prototype.hello

The class syntax is mostly sugar on top of the normal prototypical definition of a function. 类语法主要是在函数的正常原型定义之上。

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

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