在Javascript的函数原型中创建函数
如何在函数原型中正确创建函数? 我所拥有的是:在Javascript的函数原型中创建函数,javascript,function,prototype,Javascript,Function,Prototype,如何在函数原型中正确创建函数? 我所拥有的是: <body> <p id="demo"></p><script> function person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; } person.prototype.na
<body>
<p id="demo"></p><script>
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
person.prototype.name = function() {
return {
myFunc: function() {
this.firstName + " " + this.lastName;
}
}
};
var myFather = new person("John", "Doe", 50, "blue");
document.getElementById("demo").innerHTML =
"My father is " + myFather.name().myFunc;
</script>
</body>
功能人(第一、最后、年龄、眼睛){
this.firstName=first;
this.lastName=last;
这个。年龄=年龄;
this.eyeColor=眼睛;
}
person.prototype.name=函数(){
返回{
myFunc:function(){
this.firstName+“”+this.lastName;
}
}
};
var myFather=新人(“约翰”、“多伊”、50、“蓝色”);
document.getElementById(“demo”).innerHTML=
“我的父亲是”+myFather.name().myFunc;
当我运行这个函数时,它返回“我的父亲是函数(){this.firstName+”“+this.lastName;}”,但我期待着John Doe。如果需要调用函数,请将
()
添加到myFunc
。在您的示例中,您添加了对内部函数的引用
document.getElementById("demo").innerHTML = "My father is " + myFather.name().myFunc();
同时将return
添加到myFunc
。要从父作用域获取属性,请保存对this
person.prototype.name = function () {
var _this = this;
return {
myFunc: function () {
return _this.firstName + " " + _this.lastName;
}
}
};
您需要调用函数,请将
()
添加到myFunc
。在您的示例中,您添加了对内部函数的引用
document.getElementById("demo").innerHTML = "My father is " + myFather.name().myFunc();
同时将return
添加到myFunc
。要从父作用域获取属性,请保存对this
person.prototype.name = function () {
var _this = this;
return {
myFunc: function () {
return _this.firstName + " " + _this.lastName;
}
}
};
Myfunc是一个函数。当您调用它时,可以像调用myfunc()一样调用它。当您调用它时,可以像
myfunc()
那样调用它,因为您没有调用myfunc
,而且该函数不会返回任何内容。我发现这是定义funciton原型的更干净、更好的方法:
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype = {
name: function() {
return this.firstName + " " + this.lastName;
}
};
请注意,name
现在返回返回this.firstName+“”+this.lastName代码>
然后简单地说:
document.getElementById("demo").innerHTML = "My father is " + myFather.name();
您没有调用myFunc
,而且该函数不返回任何内容。我发现这是定义funciton原型的更干净、更好的方法:
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype = {
name: function() {
return this.firstName + " " + this.lastName;
}
};
请注意,name
现在返回返回this.firstName+“”+this.lastName代码>
然后简单地说:
document.getElementById("demo").innerHTML = "My father is " + myFather.name();
您没有调用myFunc
,只是返回函数本身。如果你想调用myFunc
,那么它应该myFather.name().myFunc()
什么是“函数原型”?@MarcB:是的,你没有调用myFunc
,你只是返回函数本身。如果您想调用myFunc
,那么它应该myFather.name().myFunc()
什么是“函数原型”?@MarcB:是的,甚至更干净:甚至更干净:这个解决方案很有效,谢谢!我猜我在问题中使用的“this”是不正确的。这个解决方案有效,谢谢!我猜我在问题中对“this”的用法是不正确的。