javascript - 无法使用对函数的调用方法创建对象。如何使用调用方法创建对象?
问题描述
在这里,我创建了一个构造函数。我想使用调用此函数的方法创建一个对象。我使用空对象作为当前对象并传递了一个参数。
function Circle(radius){
this.radius = radius;
this.draw = function(){
console.log('draw');
}
}
let cirlce1 = Circle.call({}, 1);
console.log(cirlce1);
我在控制台中变得不确定。我想知道我哪里出错了?
解决方案
您必须在 Circle 函数中返回当前对象。在这里,您正在创建一个等于 Circle 返回的变量。因为它没有返回任何东西,所以你得到了未定义的。因此,您只需在返回 this 的末尾添加一个 return 语句。在这种情况下,它是您最初在调用中传递的空对象。
function Circle(radius){
this.radius = radius;
this.draw = function(){
console.log('draw');
}
return this;
}
let circle = Circle.call({}, 1);
console.log(circle);
之后,您的空对象现在具有 radius 属性和 draw 方法。然后你退货。结果保存在 circle 变量中。
推荐阅读
- android - 如果未单击通知,如何使用通知删除意图并保存通知详细信息
- java - 当输入流开始读取时,输出流开始写入
- regex - 如何从数字中删除最后一位 - REGEX
- r - 在函数中连接 _n 和 _mean
- javascript - 在加载其他脚本之前替换文本
- php - $_SERVER['REMOTE_ADDR'] 给出服务器的 IP 地址而不是用户的 IP 地址
- mongodb - 在 MongoDB 的几个嵌套字段中获取最后一个数组项
- wordpress - 如何使 Wordpress 缩略图网格大小相同
- kubernetes - 在 macOS 上重新安装后 kubernetes 超时
- node.js - 错误消息:InvalidKey:密钥应至少包含一种