从今天开始记录学习ES6的知识点,这次学习的是新增:Arrow functions
Arrows以=>为简写形式,特点:
语法:
() => { ... } // no parameter x => { ... } // one parameter, an identifier (x, y) => { ... } // several parameters
例子:
var odds = evens.map(v => v + 1);
var odds = evens.map(function(v){return v + 1});
用途:
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { // (A) 'use strict'; return arr.map(function (x) { // (B) // Doesn’t work: return this.prefix + x; // (C) }); };
在严格模式下,匿名函数中的this的值为undefined,这也就是为何上面的例子会报错。
解决方法:
1.
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { var that = this; // (A) return arr.map(function (x) { return that.prefix + x; }); };
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(function (x) { return this.prefix + x; }, this); // (A) };
3.
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map(function (x) { return this.prefix + x; }.bind(this)); // (A) };
function Prefixer(prefix) { this.prefix = prefix; } Prefixer.prototype.prefixArray = function (arr) { return arr.map((x) => { return this.prefix + x; }); };
本文分享自微信公众号 - 前端黑板报(FeHeiBanBao),作者:zhuxy
原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。
原始发表时间:2015-07-13
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句