通过es6类语法创建的公共方法不可枚举。用es5和es6编写的'getname‘方法有什么区别?
function Cat(){
this.name="cat"
}
Cat.prototype.getname = function() {return this.name}
var cat = new Cat()
class Dog {
constructor(){
this.name="dog"
}
getname() {
return this.name
}
}
var dog = new Dog()
cat.__proto__.propertyIsEnumerable("getname") //true
dog.__proto__.propertyIsEnumerable("getname") //false发布于 2017-01-26 22:48:15
使用obj.property = foo将属性直接添加到对象将始终创建可枚举的属性。
ES2015类语法不能做到这一点。
要在ES5中(部分)复制ES2015功能,必须使用Object.defineProperty(Cat.prototype, 'getname', ...)添加getname方法
发布于 2017-01-26 22:48:50
正如您所说,ES6类方法是不可枚举的。另一个区别是它们是不可构造的:
new cat.__proto__.getname; // works
new dog.__proto__.getname; // throws a TypeError此外,类中的方法代码始终是strict mode代码,并且可以利用某些语言特性,如super关键字。
https://stackoverflow.com/questions/41875897
复制相似问题