代码之家  ›  专栏  ›  技术社区  ›  Advena

使用“this”而不是简单地返回一个对象来创建构造函数

  •  0
  • Advena  · 技术社区  · 7 年前

    我正在试图弄清楚为什么我们在函数构造函数中使用“this”而不是简单地返回一个对象?

    例如,这个 JSFiddle

    // Using this inside function
    function Student1(first,last) {
        this.firstName = first;
      this.lastName = last;
      this.display = function(){
        return this.firstName + " " + this.lastName;
      };
    }
    
    const harry = new Student1("Harry", "Potter");
    
    document.querySelector("div").innerHTML = harry.display();
    
    document.querySelector("div").innerHTML += "<br>";
    
    
    // Returning object
    function Studen2(first,last){
        return {
        firstName: first,
        lastName: last,
        display(){
            return this.firstName + " " + this.lastName;
        }
      };
    }
    
    const ron = new Student1("Ron", "Weasley");
    
    document.querySelector("div").innerHTML += ron.display();
    

    有人介意给我解释一下或者给我指引正确的方向吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Bart van den Burg    7 年前

    通常,您需要在类原型上定义对象方法,这样就不必在每次创建类的新实例时重新实例化它们,例如:

    function Student1(first,last) {
        this.firstName = first;
        this.lastName = last;
    }
    
    Student1.prototype.display = function() {
        return this.firstName + " " + this.lastName;
    }
    
    const harry = new Student1("Harry", "Potter");
    
    document.querySelector("div").innerHTML = harry.display();
    

    如果只返回一个(匿名)对象,它就没有原型,每次调用构造函数时都必须定义函数。

    harry instanceof Student1 // true
    ron  instanceof Student2 // false
    

    所以你不能使用instanceof。

        2
  •  2
  •   Nina Scholz    7 年前

    this 与实例化函数的原型一起工作,而简单对象在原型链中有另一个原型。它没有自己的实例化函数原型。

    您可以向原型中添加一个新方法并观察其差异。

    // Using this inside function
    function Student1(first,last) {
        this.firstName = first;
      this.lastName = last;
      this.display = function(){
        return this.firstName + " " + this.lastName;
      };
    }
    
    const harry = new Student1("Harry", "Potter");
    
    Student1.prototype.morning = function () { return 'good morning ' + this.firstName + " " + this.lastName; };
    
    console.log(harry.morning());
    
    
    
    // Returning object
    function Studen2(first,last){
        return {
        firstName: first,
        lastName: last,
        display(){
            return this.firstName + " " + this.lastName;
        }
      };
    }
    
    const ron = new Student1("Ron", "Weasley");
    
    Student2.prototype.morning = function () { return 'good morning ' + this.firstName + " " + this.lastName; };
    
    console.log(ron.morning());