TypeError: Person.greet is not a function
TypeError: Person.greet is not a function
function Person(name, age, greet) {
this.name = 'Josh';
this.age = 15;
this.greet = function(greeting) {
console.log('Hello I am ', this.name)
}
}
Person.greet();
我试图让控制台显示“你好,我是 Josh”,但我收到同样的错误消息 Person.greet 不是一个函数
这似乎是一个构造函数,而不是一个对象,因此,您需要在调用方法之前调用new
创建构造函数的实例。
// on a side note, if you're not going to use the arguments, better remove them altogether
function Person(name, age, greet) {
this.name = 'Josh';
this.age = 15;
this.greet = function(greeting) {
console.log('Hello I am ', this.name)
}
}
const person = new Person();
person.greet();
function Person(name, age, greet) {
this.name = name;
this.age = age;
this.greet = function(greeting) {
console.log('Hello I am', this.name)
}
}
const max = new Person();
max.name = 'max';
max.age = 18;
max.greet(); // Hello I am max
I realised that I was using a factory function, I was meant to create an object using the new keyword
function Person(name, age, greet) {
this.name = 'Josh';
this.age = 15;
this.greet = function(greeting) {
console.log('Hello I am ', this.name)
}
}
Person.greet();
我试图让控制台显示“你好,我是 Josh”,但我收到同样的错误消息 Person.greet 不是一个函数
这似乎是一个构造函数,而不是一个对象,因此,您需要在调用方法之前调用new
创建构造函数的实例。
// on a side note, if you're not going to use the arguments, better remove them altogether
function Person(name, age, greet) {
this.name = 'Josh';
this.age = 15;
this.greet = function(greeting) {
console.log('Hello I am ', this.name)
}
}
const person = new Person();
person.greet();
function Person(name, age, greet) {
this.name = name;
this.age = age;
this.greet = function(greeting) {
console.log('Hello I am', this.name)
}
}
const max = new Person();
max.name = 'max';
max.age = 18;
max.greet(); // Hello I am max
I realised that I was using a factory function, I was meant to create an object using the new keyword