ES6中存在的getter方法在ES6之前的alternative是什么
What is alternative before ES6 of getter method existing in ES6
Getter ES6 中的方法被定义为 METHOD 并被称为 ATTRIBUTE(调用 obj.method
而不是 obj.method(..)
)
示例:
class Job {
constructor(){
this.start=new Date();
}
get age(){
return new Date()-this.start;
}
}
然后:
var vm=new Job();
//....
vm.age // call Getter method
我的问题是:如果有的话,ES6 之前的替代方案是什么?
从 ES5 开始,您就可以使用 Object.defineProperty 定义 getter 和 setter。您的 ES6 代码本质上是以下 ES5 代码的语法糖:
function Job ( ) {
this.start = new Date;
}
Object.defineProperty( Job.prototype, 'age', {
get: function ( ) { return new Date - this.start; }
} );
在此之前,一些引擎对 getter 有非标准支持,例如 Object.prototype.__defineGetter__,它会像这样被用来复制你的功能:
Job.prototype.__defineGetter__( 'age', function ( ) {
return new Date - this.start;
} );
SpiderMonkey 也有其他一些更早的方法:
Job.prototype.age getter = function() {
return new Date - this.start;
};
// or, this one, which declares age as a variable in the local scope that acts like a getter
getter function age() { ... };
None 今天应该使用这些方法,除了 Object.defineProperty
在 ES6 中仍然非常有用。
从 ES5 开始,对象的每个 属性 都有一个 Getter 和 Setter 函数。
您可以在此处找到完整的文档:MDN - Object.defineProperty()
创建对象后,您可以定义一个新的 属性 并告知在获取和设置该值时使用哪些函数:
var obj = {};
Object.defineProperty( obj, 'propName', {
get: function() { return 42; },
set: function(newValue){ this.propName = newValue; }
});
在您的 ES6 代码中,您正在做的是定义一个新的构造函数,然后为 age
定义 get
ter。
Getter ES6 中的方法被定义为 METHOD 并被称为 ATTRIBUTE(调用 obj.method
而不是 obj.method(..)
)
示例:
class Job {
constructor(){
this.start=new Date();
}
get age(){
return new Date()-this.start;
}
}
然后:
var vm=new Job();
//....
vm.age // call Getter method
我的问题是:如果有的话,ES6 之前的替代方案是什么?
从 ES5 开始,您就可以使用 Object.defineProperty 定义 getter 和 setter。您的 ES6 代码本质上是以下 ES5 代码的语法糖:
function Job ( ) {
this.start = new Date;
}
Object.defineProperty( Job.prototype, 'age', {
get: function ( ) { return new Date - this.start; }
} );
在此之前,一些引擎对 getter 有非标准支持,例如 Object.prototype.__defineGetter__,它会像这样被用来复制你的功能:
Job.prototype.__defineGetter__( 'age', function ( ) {
return new Date - this.start;
} );
SpiderMonkey 也有其他一些更早的方法:
Job.prototype.age getter = function() {
return new Date - this.start;
};
// or, this one, which declares age as a variable in the local scope that acts like a getter
getter function age() { ... };
None 今天应该使用这些方法,除了 Object.defineProperty
在 ES6 中仍然非常有用。
从 ES5 开始,对象的每个 属性 都有一个 Getter 和 Setter 函数。 您可以在此处找到完整的文档:MDN - Object.defineProperty()
创建对象后,您可以定义一个新的 属性 并告知在获取和设置该值时使用哪些函数:
var obj = {};
Object.defineProperty( obj, 'propName', {
get: function() { return 42; },
set: function(newValue){ this.propName = newValue; }
});
在您的 ES6 代码中,您正在做的是定义一个新的构造函数,然后为 age
定义 get
ter。