JavaScript将方法添加到构造函数
为什么我不能做以下事情JavaScript将方法添加到构造函数,javascript,Javascript,为什么我不能做以下事情 function Person(name) { this.name = name; this.sayHello = function() { console.log("Hi, my name is " + this.name); }; } var me = new Person("Robert"); me.sayHello(); 输出:uncaughttypeerror:me.sayHello不是一个函数(匿名函数)@index.html:20您需
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log("Hi, my name is " + this.name);
};
}
var me = new Person("Robert");
me.sayHello();
输出:
uncaughttypeerror:me.sayHello不是一个函数(匿名函数)@index.html:20
您需要通过以下方式调用Person实例来实例化它:var me=new Person(“Robert”)代码>
您使用伪经典实例化模式编写的构造函数。这在代码中的工作方式是,当您使用关键字new
时,它会在幕后调用Person,并添加两行代码。
它将您的功能转化为:
function Person(name) {
// The new keyword adds this line
// var this = Object.create(Person.prototype);
this.name = name;
this.sayHello = function() {
"Hi, my name is " + this.name;
};
// and this line
// return this;
}
如果没有new
关键字,您实际上不会从函数中返回任何内容
你可能没有得到你期望的其他原因。您的sayHello
函数只创建了一个字符串。我假设您希望将此字符串记录到控制台,因此修改您的函数,如下所示:
this.sayHello = function() {
console.log("Hi, my name is " + this.name);
}
您的最终代码应该如下所示:
function Person(name) {
this.name = name;
this.sayHello = function() {
console.log("Hi, my name is " + this.name);
};
}
var me = new Person("Robert");
me.sayHello();
“new”关键字在构造器函数“Person”的上下文中创建临时对象“this”。如果没有“new”,则表示全局对象(大多数情况下)
调用:newperson(“someone”)返回这个临时对象“this”,所以您可以基于它获取对象
如果没有关键字“new”,则构造函数只返回“undefined”(如果函数体中没有任何“return”关键字)。newperson(“Robert”)代码>抱歉将问题更新为我真正的意思。我只是发布了一个关于你问题的快速答案,同时更新得更彻底。它现在能更好地回答您的问题吗?好的,按照您指定的更新代码。获取错误:uncaughttypeerror:me.sayHello不是一个函数
Mmm,我想我可能把你弄糊涂了。再看看我的答案,下面的代码就是你想要的