【发布时间】:2018-08-20 19:48:22
【问题描述】:
我无法在我创建的构造函数中调用方法。这是函数和我尝试调用它...
var Cohort = function(program, campus, number, students){
this.program = program,
this.campus = campus,
this.number = number,
this.students = students,
function sayName(){
return `This cohort is called ${program}, ${campus}, ${number}.`
},
function takeAttendance(){
return console.log(students)
}
}
var cohort1 = new Cohort("w", "pr", 27, ['devin', 'ben', 'bob'])
var cohort2 = new Cohort('w', 'pr', 31, ["Brendan Eich", "Dan Abramov", "Wes Bos", "Kent Dodds"])
cohort1.sayName()
控制台说群组1.sayName 不是一个函数。
【问题讨论】:
-
如果您想以指定的方式使用它,您需要将该方法添加到 Cohort 的原型中。请参阅Object.prototype 了解更多信息。
-
在构造函数中声明函数不会使其成为构造对象的属性值。这只是一个本地功能。您可以通过添加
this.sayName = sayName;使其成为属性。 -
@Pointy 但这不会只打印出提到的变量的局部值吗?如果要更改
this.program,sayName的输出不会反映它,对吗?换句话说,我认为您发布的内容会起作用,但我不确定它是否反映了 OP 的意图(尽管谁知道)。 -
@rmlan 没有; “sayName”函数指的是构造函数参数,而不是对象属性。这些永远不会改变。
-
@Pointy 我就是这么说的。我不能确定,但我有一种感觉与 OP 真正想要的东西存在争议。
标签: javascript function methods constructor