首页 > 解决方案 > 使用“this”创建构造函数,而不是简单地返回一个对象

问题描述

我的单词知识可能不足以自己在www上找到解释。所以如果这可能是重复的,请原谅我。

我目前正试图弄清楚为什么我们在函数构造函数中使用“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();

有人介意解释或指导我正确的方向吗?

标签: javascriptfunctionobjectthis

解决方案


this使用 instanciable 函数的原型,而简单对象在原型链中有另一个原型。它没有自己的实例化函数原型。

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

// 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());


推荐阅读