Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中为函数创建原型?_Javascript_Function_Oop_Object_Prototype - Fatal编程技术网

在JavaScript中为函数创建原型?

在JavaScript中为函数创建原型?,javascript,function,oop,object,prototype,Javascript,Function,Oop,Object,Prototype,我可能做错了,但这似乎是一个使用原型的好地方 我有一份电子邮件表格。将要验证的表单的每个输入都有一个对象。这个物体的原型是 var contactInput = function(placeholder, validateFuntion) { this.placeholder = placeholder; this.value = ""; var error = true; this.setError = function(errorValue) { if(typeof(

我可能做错了,但这似乎是一个使用原型的好地方

我有一份电子邮件表格。将要验证的表单的每个输入都有一个对象。这个物体的原型是

var contactInput = function(placeholder, validateFuntion) {
  this.placeholder = placeholder;
  this.value = "";
  var error = true;
  this.setError = function(errorValue) {
    if(typeof(errorValue) === "boolean") {
      error = errorValue;
    } else {
      return false;
      console.log(".setError argument must be boolean.");
    }
  };
  this.getError = function() {
     return error;
  }
  var errorMessage = "";
    this.setErrorMessage = function(errorMessageValue) {
    if(typeof(errorMessageValue) === "string") {
      errorMessage = errorMessageValue;
    } else {
      return false;
      console.log(".setErrorMessage argument must be string.");
    }
  };
  this.getErrorMessage = function() {
     return errorMessage;
  }
  this.validateFunction = validateFunction;
}
我在这里遇到的问题与
validateFunction
属性有关。其中有三种输入。它们的每一个验证功能都非常相似。它们只是在验证值的操作上有所不同,以及在为false时产生的错误消息

其中一个看起来像这样

function(inputValue) {
    if (inputValue === "") {
      this.error = true;
      this.errorMessage = "You did not provide a name.";
      return "error.png";
    } else if (inputValue.length > 50) {
      this.error = true;
      this.errorMessage = "Name must be under 50 characters.";
      return "error.png";
    } else {
      this.error = false;
      return "tick.png";
    }
      }
function(inputValue) {
    if (inputValue === "") {
      this.error = true;
      this.errorMessage = "You did not provide an email.";
      return "error.png";
    } else if ( !/(.+)@(.+){2,}\.(.+){2,}/.test(inputValue) ) {
      this.error = true;
      this.errorMessage = "The email you provided was invalid.";
      return "error.png";
    } else {
      this.error = false;
      return "tick.png";
    }
      }
另一个看起来像这样

function(inputValue) {
    if (inputValue === "") {
      this.error = true;
      this.errorMessage = "You did not provide a name.";
      return "error.png";
    } else if (inputValue.length > 50) {
      this.error = true;
      this.errorMessage = "Name must be under 50 characters.";
      return "error.png";
    } else {
      this.error = false;
      return "tick.png";
    }
      }
function(inputValue) {
    if (inputValue === "") {
      this.error = true;
      this.errorMessage = "You did not provide an email.";
      return "error.png";
    } else if ( !/(.+)@(.+){2,}\.(.+){2,}/.test(inputValue) ) {
      this.error = true;
      this.errorMessage = "The email you provided was invalid.";
      return "error.png";
    } else {
      this.error = false;
      return "tick.png";
    }
      }
我想为验证函数创建一个原型,然后我可以使用它创建三个验证函数实例。然后,我将使用输入的原型(我已经拥有的原型)创建三个输入实例,使用我创建的验证函数实例设置输入实例的
validateFunction
方法


我无法想象一个人将如何完成它,或者是否应该这样做。即使不应该这样做,我如何才能做到这一点呢?

首先,您的术语有些混乱,我不会在这里称任何东西为“函数原型”

Prototype是一个对象,它与Prototype一起用于创建其他对象。 在javascript中,恰好使用
函数
作为对象的构造函数

关于您的实施的几个注意事项:

  • 返回后的代码将永远不会执行。而
    console.log
    是一种错误通知方式(最好抛出错误):

  • 就OOP而言,使用getter和setter是不好的,这样就可以向世界公开对象状态。更好的方法是把物体当作一台微型计算机,一个你可以要求做一些工作的黑匣子。 所有初始化数据都被传递到构造函数中,因此您不需要setter,并且与对象内的数据相关的工作由对象完成,因此您也不需要getter

  • 有两种方法可以实现稍微不同的行为-继承,其中子类实现差异或组合,其中差异被移动到另一个对象。 使用什么取决于情况

  • 实现输入的一种可能方法是使用继承:

    function ContactInput(selector, placeholder) {
      // properties are prefixed with underscore to notify the programmer that they are
      // 'private' (should not be accessed outside of this class or subclasses)
      this._element = document.querySelector(selector);
      this._placeholder = placeholder;
    }
    
    ContactInput.prototype.validate() {
        // this should be implemented in child classes
        throw 'Not implemented';
    }
    
    // Private method (prefixed with underscore), also to be used only by this object
    ContactInput.prototype._renderSuccess(message, image) {
        message = message || "";
        image = image || "tick.png";
        // show the success div near the element (actually it is better to use css, 
        // so it will be not necessary to pass the `tick.png` and `error.png`
        // around, you could just change the element's css class here to show the tick)
    }
    
    // Private
    ContactInput.prototype._renderError(message, image) {
        message = message || "Validation error";
        image = image || "error.png";
        // show the error div near the element
    }
    
    // Private
    ContactInput.prototype._getValue() {
        return this._element.value;
    }
    
    function NameInput(placeholder) {
        ContactInput.call(this, placeholder);
    }
    NameInput.prototype = Object.create(ContactInput.prototype);
    
    NameInput.prototype.validate() {
        var value = this._getValue();
        if (!value) {
            return this.renderError("You did not provide a name.", 'error.png');
        }
        if (value.length > 50) {
            return this.renderError("Name must be under 50 characters.", 'error.png');
        }
        return this.renderSuccess();
    }
    
    function EmailInput(placeholder) {
        ContactInput.call(this, placeholder);
    }
    EmailInput.prototype = Object.create(ContactInput.prototype);
    
    EmailInput.prototype.validate() {
        var value = this._getValue();
        if (!value) {
            return this.renderError("You did not provide an email.", 'error.png');
        }
        if ( !/(.+)@(.+){2,}\.(.+){2,}/.test(value) ) {
            return this.renderError("The email you provided was invalid.", 'error.png');
        }
        return this.renderSuccess();
    }
    
    我不确定如何使用
    占位符
    ,所以我把它留在了基类中。 根据使用情况,它只能是
    NameInput
    的属性(或
    EmailInput

    现在您可以执行以下操作:

    var inputs = [
        new NameInput('x'),
        new EmailInput('y')
    ];
    inputs.forEach(function(input) {
        input.validate();
    });
    
    请注意,您不必在其他地方执行诸如
    input->setError('xxx')
    input->getError('xxx')
    之类的操作。
    您只需创建对象,给它一些数据,然后让它根据这些数据工作。

    首先,您的术语有些混乱,我不会在这里称之为“函数原型”

    Prototype是一个对象,它与Prototype一起用于创建其他对象。 在javascript中,恰好使用
    函数
    作为对象的构造函数

    关于您的实施的几个注意事项:

  • 返回后的代码将永远不会执行。而
    console.log
    是一种错误通知方式(最好抛出错误):

  • 就OOP而言,使用getter和setter是不好的,这样就可以向世界公开对象状态。更好的方法是把物体当作一台微型计算机,一个你可以要求做一些工作的黑匣子。 所有初始化数据都被传递到构造函数中,因此您不需要setter,并且与对象内的数据相关的工作由对象完成,因此您也不需要getter

  • 有两种方法可以实现稍微不同的行为-继承,其中子类实现差异或组合,其中差异被移动到另一个对象。 使用什么取决于情况

  • 实现输入的一种可能方法是使用继承:

    function ContactInput(selector, placeholder) {
      // properties are prefixed with underscore to notify the programmer that they are
      // 'private' (should not be accessed outside of this class or subclasses)
      this._element = document.querySelector(selector);
      this._placeholder = placeholder;
    }
    
    ContactInput.prototype.validate() {
        // this should be implemented in child classes
        throw 'Not implemented';
    }
    
    // Private method (prefixed with underscore), also to be used only by this object
    ContactInput.prototype._renderSuccess(message, image) {
        message = message || "";
        image = image || "tick.png";
        // show the success div near the element (actually it is better to use css, 
        // so it will be not necessary to pass the `tick.png` and `error.png`
        // around, you could just change the element's css class here to show the tick)
    }
    
    // Private
    ContactInput.prototype._renderError(message, image) {
        message = message || "Validation error";
        image = image || "error.png";
        // show the error div near the element
    }
    
    // Private
    ContactInput.prototype._getValue() {
        return this._element.value;
    }
    
    function NameInput(placeholder) {
        ContactInput.call(this, placeholder);
    }
    NameInput.prototype = Object.create(ContactInput.prototype);
    
    NameInput.prototype.validate() {
        var value = this._getValue();
        if (!value) {
            return this.renderError("You did not provide a name.", 'error.png');
        }
        if (value.length > 50) {
            return this.renderError("Name must be under 50 characters.", 'error.png');
        }
        return this.renderSuccess();
    }
    
    function EmailInput(placeholder) {
        ContactInput.call(this, placeholder);
    }
    EmailInput.prototype = Object.create(ContactInput.prototype);
    
    EmailInput.prototype.validate() {
        var value = this._getValue();
        if (!value) {
            return this.renderError("You did not provide an email.", 'error.png');
        }
        if ( !/(.+)@(.+){2,}\.(.+){2,}/.test(value) ) {
            return this.renderError("The email you provided was invalid.", 'error.png');
        }
        return this.renderSuccess();
    }
    
    我不确定如何使用
    占位符
    ,所以我把它留在了基类中。 根据使用情况,它只能是
    NameInput
    的属性(或
    EmailInput

    现在您可以执行以下操作:

    var inputs = [
        new NameInput('x'),
        new EmailInput('y')
    ];
    inputs.forEach(function(input) {
        input.validate();
    });
    
    请注意,您不必在其他地方执行诸如
    input->setError('xxx')
    input->getError('xxx')
    之类的操作。
    您只需创建对象,给它一些数据,然后让它根据这些数据工作。

    我认为您没有以典型的方式使用术语
    prototype
    。听起来更像是一个公共/共享函数,您可以将一些参数传递给它,而不是将大部分代码复制到几个基本相同但略有不同的函数中。在Javascript中,这只是一个共享函数,而不是一个同样可以工作的
    原型
    @jfriend00。然而,有几个原因让我想这样做。如果这是可能的,各个功能将“持续”。这将使我能够调用每个函数,而不必提供多个参数。在这种情况下,我的论点从5倒数到1。你可以创建一个包含98%功能的公共函数体,然后创建三个shell函数,它们除了将正确的参数传递给你的公共函数之外什么都不做。然后,你可以两全其美。一个简单的函数,用于在一个共享functoid中调用每个验证器和公共代码。仅供参考,这是基本的编程结构(将公共代码分解为共享函数)。如果这是你不熟悉的东西,那么你可能会从某种编程课程中受益,因为它将真正帮助你学习更多的t