简体   繁体   English

JavaScript原型继承无法正常工作

[英]Javascript prototype inheritance not working

This is not the actual project i am working on but simple code to understand what am i doing wrong. 这不是我正在进行的实际项目,而是了解我在做什么错的简单代码。

I have created a object named NumSelector and trying to use method validator which i have inherited using prototype. 我创建了一个名为NumSelector的对象,并尝试使用通过原型继承的方法验证器 I get error "validator is not defined" 我收到错误“验证器未定义”

function NumSelector(num)
{
    if(validator(num))
      console.log("NUmber is positive");
    else
      console.log("Number s negative");
}

NumSelector.prototype.validator = function(num)
{
  if(num>0)
    return true;
  else
    return false;
};

Use this.validator() in the if condition instead of validator() 在if条件中使用this.validator()而不是validator()

function NumSelector(num)
{
    if(this.validator(num))
      console.log("NUmber is positive");
    else
      console.log("Number s negative");
}

NumSelector.prototype.validator = function(num)
{
  if(num>0)
    return true;
  else
    return false;
};

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

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