我正在尝试在Javascript中创建自定义构造函数,但我似乎无法理解为什么控制台不会记录“调查”的'字母'属性由构造函数“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**
我在这里做错了什么?非常感谢你们的帮助,谢谢。
答案 0 :(得分:1)
在构造函数内部函数this
指的是正在创建的obj。所以this.charAt(0)
是不正确的。因为对象对象在其原型链中没有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;`