Javascript 带有静态方法的JS类看不到静态setter
我有一个简单的代码-Javascript 带有静态方法的JS类看不到静态setter,javascript,class,static,ecmascript-6,Javascript,Class,Static,Ecmascript 6,我有一个简单的代码- 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 t
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
为什么“key”静态方法中未定义“getDic”getter
谢谢 在类中定义
static
属性时,它会将其绑定到构造函数
,因此当您执行new Repo()
时,返回值不包含static
方法,而是new Repo()。构造函数将包含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
属性用作函数
通过将set
键置于函数属性之前,可以将函数设置为set
属性。。。这意味着函数在对象上设置为get
。defineProperty
让我们看看使用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
“严格使用”;
var_createClass=function(){function defineProperties(target,props){for(var i=0;i var someParam=arguments.length我遇到了一个非常类似的问题;事实证明,这个
并没有像您期望的那样引用静态类。使用实际的类名可以修复它。因此:
class Repo {
. . .
static key(key){
return Repo.getDic[key];
}
}
通过将this
替换为类名,它应该可以正常工作。你认为static
有什么作用?@Bergi允许使用方法/getter/setter而无需实例化类…?对。那么你希望静态方法如何访问实例特定的数据?@FelixKling你完全正确!谢谢u!:)是的。这就是为什么在Repo
上访问静态属性,而不是在newRepo
上访问静态属性的原因(正如您现在在中编辑的)。您很可能根本不想使用静态
。感谢您的回答,我编辑了我的问题以更好地反映问题。您对此有什么意见吗?谢谢!