【问题标题】:Constructors and how call works in Javascript构造函数以及调用在 Javascript 中的工作方式
【发布时间】:2017-03-26 15:38:30
【问题描述】:

我有几个关于代码的问题。

1) 在 student 构造函数中,Person.call(this, firstName) 是否允许学生访问 person 的方法?还是会改变 this 的上下文?

2) 我假设 Student.prototype = Object.create(Person.prototype) 让我们可以访问 person 的方法和属性?

我很难理解调用方法。

var Person = function(firstName) {
  this.firstName = firstName;
};

Person.prototype.walk = function(){
  console.log("I am walking!");
};


function Student(firstName, subject) {
  Person.call(this, firstName);
  this.subject = subject;
};

Student.prototype = Object.create(Person.prototype); // See note belo
Student.prototype.constructor = Student;

Student.prototype.sayHello = function(){
  console.log("Hello, I'm " + this.firstName + ". I'm studying "
              + this.subject + ".");
};

【问题讨论】:

    标签: javascript object call


    【解决方案1】:

    1) 不,它设置 this 值并传递一个参数,但是因为它将 Personthis 值设置为 thisStudent 中的任何值,它也可以给出 Person访问Student,但不能反过来。

    call(this-value, [arg1,arg2])apply(this-value, [[arg1,arg2]]) 所做的所有事情都是使用给定的 this 值和参数调用函数。

    2) 是的,Student.prototype = Object.create(Person.prototype) 复制了Person 的原型,并将其设置为Student 的原型,给Student 提供了与Person 相同的原型方法,但是一个副本,而不是相同的引用。

    【讨论】:

    • 感谢 adeneo 很好的解释!我还有几个问题。如果我创建 var student1 = new Student("john", "physics");创建 student1 对象时,我们调用传入 'this' (student1) 和名称 john 的 person 函数。所以我们在对象 person1 之外调用了一个函数,允许我们共享函数
    猜你喜欢
    • 2018-08-20
    • 2013-05-08
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2021-08-21
    • 2013-01-15
    相关资源
    最近更新 更多