【问题标题】:Function Constructor - add function using prototype gives - Uncaught SyntaxError: Unexpected token {函数构造函数 - 使用原型添加函数 - Uncaught SyntaxError: Unexpected token {
【发布时间】:2018-12-08 07:10:24
【问题描述】:

我尝试使用原型链接将函数y() 添加到对象构造函数x 中。它导致unexpected 错误:

意外令牌{

function x(a, b) {
  this.a = a
  this.b = b
}
x.prototype.y(){
  console.log('hello')
}

我希望函数 x 为:

function x(a, b) {
  this.a = a; 
  this.b = b; 

  y() 
}

【问题讨论】:

    标签: javascript object prototype object-construction function-constructor


    【解决方案1】:

    您没有将 y 分配给函数。您的语法无效。相反,请使用anonymous function:

    x.prototype.y = function() {...}

    请参阅下面的工作示例:

    function x(a, b) {
      this.a = a
      this.b = b
    }
    
    x.prototype.y = function() {
      console.log('hello');
    }
    
    let a = new x(1, 2);
    a.y();

    如果你希望方法是静态的,你可以省略prototype:

    function x(a, b) {
      this.a = a
      this.b = b
    }
    
    x.y = function() {
      console.log('hello');
    }
    
    x.y();

    【讨论】:

    • 我希望函数 x 为 - ƒ x(a, b) { this.a = a ;这个.b = b; y() }
    • @MonicaAcha 然后不要使用prototype 查看更新后的答案
    【解决方案2】:

    您不能使用该语法 - 您需要像这样声明它:

    x.prototype.y = function() {
        console.log("Hello");
    };
    

    这是因为您将匿名函数分配给对象的属性 - 就像您在构造函数中执行此操作一样。这是您的代码的完整示例:

    function x(a, b) {
      this.a = a
      this.b = b
    }
    x.prototype.y = function() {
      console.log("Hello");
    };
    
    var anX = new x("a", "b");
    anX.y();

    【讨论】:

    • 我希望函数 x 为 - ƒ x(a, b) { this.a = a ;这个.b = b; y() }
    • @MonicaAcha 所以你只想在对象构造函数中分配函数?只需this.y = function() { console.log("Hello"); };
    猜你喜欢
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 2012-05-17
    相关资源
    最近更新 更多