Jon*_*cas 23 javascript prototype ecmascript-6 arrow-functions
当ES6箭头函数似乎不适用于使用prototype.object将函数赋值给对象时.请考虑以下示例:
function Animal(name, type){
this.name = name;
this.type = type;
this.toString = () => `${this.name} is a ${this.type}`;
}
var myDog = new Animal('Max', 'Dog');
console.log(myDog.toString()); //Max is a Dog
Run Code Online (Sandbox Code Playgroud)
在对象定义中显式使用箭头函数,但使用带有Object.prototype语法的箭头函数不会:
function Animal2(name, type){
this.name = name;
this.type = type;
}
Animal2.prototype.toString = () => `${this.name} is a ${this.type}`;
var myPet2 = new Animal2('Noah', 'cat');
console.log(myPet2.toString()); //is a undefined
Run Code Online (Sandbox Code Playgroud)
正如概念验证一样,使用带有Object.prototype语法的Template字符串语法可以正常工作:
function Animal3(name, type){
this.name = name;
this.type = type;
}
Animal3.prototype.toString = function(){ return `${this.name} is a ${this.type}`;}
var myPet3 = new Animal3('Joey', 'Kangaroo');
console.log(myPet3.toString()); //Joey is a Kangaroo
Run Code Online (Sandbox Code Playgroud)
我错过了一些明显的东西吗 我觉得示例2应该在逻辑上起作用,但我对输出感到困惑.我猜这是一个范围问题,但我被输出'是一个未定义的'抛弃了.
Ami*_*mit 26
箭头功能提供词汇this.它使用在this评估函数时可用的值.
它在逻辑上等效于(以下是无效的代码,因为您不能命名变量this):
(function(this){
// code that uses "this"
})(this)
Run Code Online (Sandbox Code Playgroud)
在第一个示例中,箭头函数位于构造函数中,并this指向新生成的实例.
在第3个示例中,未使用箭头函数,标准this行为始终有效(函数作用域中的此行为).
在第二个示例中,您使用箭头函数,但在其评估的范围内,this是全局/未定义的.
常规函数返回对当前 JavaScript 对象的引用,但箭头函数返回对全局窗口对象的引用。
常规函数可以很好地处理使用 new 关键字的对象。它们具有构造函数,可以在对象创建期间初始化值。它可以使用原型链来管理,但箭头函数没有构造函数、原型链。它们不能很好地处理物体。它们不能与 new 关键字一起使用来分配内存。
在第一个示例中,您将箭头键函数写入常规函数内,然后您将获得输出。
function Animal2(name, type){
this.name = name;
this.type = type;
}
Animal2.prototype.toString = function(){
return () => `${this.name} is a ${this.type}`;
}
var myPet2 = new Animal2('Noah', 'cat');
console.log(myPet2.toString()()); //Noah is a catRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7813 次 |
| 最近记录: |