在 Javascript 的函数原型中创建函数
Creating functions in function prototypes for Javascript
如何在函数原型中正确创建函数?
我有的是:
<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>
当我 运行 这个 returns "My father is function () { 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 是一个函数。调用的时候,像myfunc()
这样调用
您没有调用 myFunc
而且该函数也没有 return 任何东西。我发现这种定义函数原型的方法更清晰、更好:
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
现在 returns return this.firstName + " " + this.lastName;
。
然后简单地:
document.getElementById("demo").innerHTML = "My father is " + myFather.name();
如何在函数原型中正确创建函数? 我有的是:
<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>
当我 运行 这个 returns "My father is function () { 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 是一个函数。调用的时候,像myfunc()
您没有调用 myFunc
而且该函数也没有 return 任何东西。我发现这种定义函数原型的方法更清晰、更好:
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
现在 returns return this.firstName + " " + this.lastName;
。
然后简单地:
document.getElementById("demo").innerHTML = "My father is " + myFather.name();