javascript - Javascript原型问题,如何在原型中调用没有这个的函数?
问题描述
let Person = function (name, age) {
this.name = name;
this.age = age;
};
Person.prototype.testProto = function () {
console.log(this.name + " == " + this.age);
let xx = function() {
console.log("in xx");
}
};
let person = new Person("Jake",49);
person.testProto();
如果我用“this.xx”更改“let xx”并用 person.xx() 调用它,这将起作用;
但是不使用“this”,当 person.testProto.xx() 不起作用时,怎么可能调用它?
谢谢
解决方案
从函数内部返回 xx 变量。
这将调用 testProto 函数和 xx 函数而不使用this
.
let Person = function(name, age) {
this.name = name;
this.age = age;
};
Person.prototype.testProto = function() {
console.log(this.name + " == " + this.age);
let xx = function() {
console.log("in xx");
}
return xx;
};
let person = new Person("Jake", 49);
person.testProto()();
推荐阅读
- javascript - 如何从 Angular Material 日期选择器中 MomentDateAdapter 操作的输入中获取有效性值?
- sql - 如何查找员工的资历级别 level0, level1........ leveln manager
- spring-kafka - 如果代理失败,spring kafka API 会自动尝试重新连接吗?
- java - 不能“嵌套”ResultSet 查询吗?或在循环中使用查询?
- maven - Sonatype nexus:根据存储库名称创建角色
- postgresql - 将多行插入具有默认值的列的表中
- python - ValueError:无法将字符串转换为浮点数:'Q'
- jquery - 正则表达式选择器的问题
- wordpress - 在 single.php 中自动加载帖子
- python - 将 dataFrame 与日期格式进行比较时的问题