如何解决如何在Javascript原型中更改变量的值
请检查以下代码,让我知道我错过了什么。
function Student() {
this.name = "John";
this.type = "Regular";
}
Student.prototype.changeType = function(givenType) {
this.type = givenType;
}
Student.prototype.changeType('Part-Time');
var William = new Student();
console.log(William.type); //Regular
控制台期望值为Part-Time
解决方法
编辑::如果要为所有当前和将来的实例设置类型,则可以尝试存储所有实例。添加新学生时,您必须对其进行更新。 JavaScript不知道如何仅通过类名来获取当前和将来的所有对象。
function Student() {
this.name = "John";
this.type = "Regular";
Student.instances.push(this); // Add
}
Student.prototype.changeType = function(givenType) {
this.type = givenType;
}
Student.instances = []; // Keep track
Student.changeAllTypes = function(type) {
Student.instances.forEach(function(instance) {
instance.changeType(type);
});
};
var William = new Student();
Student.changeAllTypes('Part-Time');
console.log(William.type); // Part-Time
执行此操作的正确方法是仅在对象实例化时传入适当的参数。
function Student(name,type) {
this.name = name;
this.type = type;
}
var william = new Student('William','Part-Time');
console.log(william.type); // Part-Time
原型与实例不同。
function Student() {
this.name = "John";
this.type = "Regular";
}
Student.prototype.changeType = function(givenType) {
this.type = givenType;
}
Student.prototype.changeType('Part-Time');
var William = new Student();
console.log(Student.prototype.type); // Part-Time
如果要更改类型,则需要将属性设置为William。
function Student () {
this.name = "John";
this.type = "Regular";
}
Student.prototype.changeType = function (givenType) {
this.type = givenType;
}
var William = new Student();
William.changeType('Part-Time');
console.log(William.type); // Part-Time
或者您可以创建一个本机ES6类,这使此操作更容易。
class Student {
constructor(name = 'John',type = 'Regular') {
this.name = name;
this.type = type;
}
setType(type) {
this.type = type;
}
getType() {
return this.type;
}
}
var william = new Student();
william.setType('Part-Time');
console.log(william.getType()); // Part-Time
,
如果未在对象本身上设置属性值,则JS仅检查原型链的下一级。
您是在原型上而不是对象本身上调用undefined
。
构造函数在对象本身上设置属性。
呼叫changeType
会产生预期的效果。
我认为您需要一个结构,该结构的方法引用实例(this) constructor
的{{1}}。然后,下一个prototype
实例将具有先前调用的实例方法所调用的属性。
new
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。