属性 在我的自定义构造函数中无法正常运行 - Javascript
property not functioning properly in my custom constructor - Javascript
我正在尝试在 Javascript 中创建自定义构造函数,但我似乎不明白为什么控制台不会记录 'Letters' "Investigating" 的 属性 由构造函数创建 "Verb":
function Verb (tense, transitivity) {
this.tense = tense;
this.transitivity = transitivity;
**this.letter1 = this.charAt(0);
this.letter2 = this.charAt(2);
this.letter3 = this.charAt(4);
this.Letters = this.letter1 + " " + this.letter2 + " " + this.letter3;**
}
var Investigating = new Verb ("present", "transitive");
console.log(Investigating.tense); // present
**console.log(Investigating.Letters); //console doesn't log anything**
我在这里做错了什么?非常感谢你们的帮助,谢谢。
在构造函数中 this
指的是正在创建的对象。所以 this.charAt(0)
是 incorrect.since Object 对象在其原型链中没有 charAt 方法。(字符串和数组有这个方法)。我想你正在尝试做。
this.letter1 = this.transitivity.charAt(0);
this.letter2 = this.transitivity.charAt(2);
this.letter3 = this.transitivity.charAt(4);
this.Letters = this.letter1 + " " + this.letter2 + " " + this.letter3;`
我正在尝试在 Javascript 中创建自定义构造函数,但我似乎不明白为什么控制台不会记录 'Letters' "Investigating" 的 属性 由构造函数创建 "Verb":
function Verb (tense, transitivity) {
this.tense = tense;
this.transitivity = transitivity;
**this.letter1 = this.charAt(0);
this.letter2 = this.charAt(2);
this.letter3 = this.charAt(4);
this.Letters = this.letter1 + " " + this.letter2 + " " + this.letter3;**
}
var Investigating = new Verb ("present", "transitive");
console.log(Investigating.tense); // present
**console.log(Investigating.Letters); //console doesn't log anything**
我在这里做错了什么?非常感谢你们的帮助,谢谢。
在构造函数中 this
指的是正在创建的对象。所以 this.charAt(0)
是 incorrect.since Object 对象在其原型链中没有 charAt 方法。(字符串和数组有这个方法)。我想你正在尝试做。
this.letter1 = this.transitivity.charAt(0);
this.letter2 = this.transitivity.charAt(2);
this.letter3 = this.transitivity.charAt(4);
this.Letters = this.letter1 + " " + this.letter2 + " " + this.letter3;`