我有一个简单的代码-
class Repo {
constructor(someParam = null) {
this.getDic = someParam;
}
static set getDic(ref){
this.ref = ref;
}
static get getDic(){
return this.ref;
}
static key(key){
return this.getDic[key];
}
}
let newRepo = new Repo({yeah: 'baby'});
Repo.key('yeah') // Uncaught TypeError: Cannot read property 'yeah' of undefined为什么'getDic‘getter在'key’静态方法中没有定义?
谢谢!
发布于 2016-03-17 21:21:50
当您在类中定义static属性时,它将其绑定到constructor,因此当您执行new Repo()操作时,返回值将不包含static方法,但new Repo().constructor将包含static方法
let newRepo = new Repo({yeah: 'baby'});
Repo.key // defined
newRepo.key // not defined
newRepo.constructor.key // defined还有一件事:Repo.key === newRepo.constructor.key。因此,通过创建一个static属性(就像在c#等其他语言中一样),该属性在作用域中存在一次,但这是一个完全不同的问题:)
编辑:
代码不能正常工作的原因是因为您将get属性用作function。
通过将set键放在函数属性之前,可以将函数设置为set属性...这意味着该函数在Object.definePropery上被设置为get
让我们看一下使用babel转换es6
'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 Repo = function () {
function Repo() {
var someParam = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
_classCallCheck(this, Repo);
this.getDic = someParam;
}
_createClass(Repo, null, [{
key: 'key',
value: function key(_key) {
console.log(this.constructor.getDic);
return this.getDic[_key];
}
}, {
key: 'getDic',
set: function set(ref) {
this.ref = ref;
},
get: function get() {
return this.ref;
}
}]);
return Repo;
}();
var newRepo = new Repo({ yeah: 'baby' });
Repo.key('yeah'); // Uncaught TypeError: Cannot read property 'yeah' of undefined长话短说,只要使用Repo.key = 'heya'就可以了。
发布于 2020-07-18 05:17:37
我遇到了一个非常类似的问题;事实证明this并不像您期望的那样引用静态类。使用实际的类名可以修复它。所以:
class Repo {
. . .
static key(key){
return Repo.getDic[key];
}
}通过用this替换类名,它应该可以正常工作。
https://stackoverflow.com/questions/36061670
复制相似问题