我最近发现了两种在JavaScript ES6中向类添加方法的方法。以下是它们的简要说明:
class SomeClass {
someMethod(arg) {
console.log(this.anotherMethod);
// This will produce an error because 'this' is undefined here.
}
anotherMethod = (arg) => {
// does stuff
}
}
请问有人能给我一个好的解释,解释这里到底发生了什么,以及语法的含义是什么?我从babel tutorial中理解到,在ES6中箭头
=>
表示函数。但我认为还有其他事情正在发生。具体来说,如果我没有弄错的话,如果我尝试通过
this
关键字访问someMethod()
,它将无法工作。我认为关键在于一种解释,我无法从Babelify ES6教程中理解:
这是否意味着箭头符号将把函数分配给其周围范围的this?因此,如果您在类的范围内使用箭头,则该函数被分配给指向该对象的this吗?与函数不同,箭头共享其周围代码的词法this。
我通过Babelify的ES6 repl运行了上面的示例代码。我无法完全理解这段代码。在我的看法中,使用箭头语法创建的方法被添加到了新的Class=Object本身,而使用非箭头语法创建的方法被添加到了Class=Object的原型中。
有没有人能给出一个简洁明了的解释,说明二者之间的区别以及下面的代码在做什么?
"use strict";
var _createClass = (function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var SomeClass = (function () {
function SomeClass() {
_classCallCheck(this, SomeClass);
this.anotherMethod = function (dog) {
// do stuff
};
}
_createClass(SomeClass, [{
key: "someMethod",
value: function someMethod(arg) {
console.log(this.anotherMethod);
// This will produce an error b/c this is undefined here.
}
}]);
return SomeClass;
})();