繁体   English   中英

如何在 Javascript 原型中更改变量的值

[英]How to change value for a variable in Javascript prototype

请检查下面的代码,让我知道我错过了什么。

 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 只会检查原型链的下一级。

您是在原型上调用changeType ,而不是在对象本身上调用。

构造函数在对象本身上设置属性。

调用William.changeType("Part-Time")会产生预期的效果。

我想你想要一个结构,它有一个方法来引用实例(这个) constructorprototype 然后下一个new实例将具有由先前调用的实例方法调用的属性。

 function Student(name = null, type = null){ this.changeName = name=>{ this.constructor.prototype.name = name; return this; } this.changeType = type=>{ this.constructor.prototype.type = type; return this; } if(name !== null)this.changeName(name); if(type !== null)this.changeType(type); } const john = new Student('John', 'Part-Time'); console.log(john.name+' -> '+john.type); const bob = new Student('Bob'); console.log(bob.name+' -> '+bob.type); const joe = new Student('Joe', 'Full-Time'); console.log(joe.name+' -> '+joe.type); const dan = new Student('Dan'); console.log(dan.name+' -> '+dan.type);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM