ES6中Class的一些个人记录

版权声明:如果这篇文章对你有所帮助,请点个赞~~~ https://blog.csdn.net/qq_35087256/article/details/83387528

1.Class的内部所有定义的方法,都是不可枚举的。

const funName = 'fun';
//类Demo		
class Demo{
	constructor(arg) {
	    
	}
	say(){
		
	}
	speak(){
		
	}
	[funName](){
		
	}
}

console.log( Object.keys(Demo.prototype) )	//[]
console.log(Object.getOwnPropertyNames(Demo.prototype))//["constructor", "say", "speak", "fun"]


//构造函数F
function F(){}
F.prototype.say = function(){};
F.prototype.speak = function(){}
F.prototype[funName] = function(){}

console.log( Object.keys(F.prototype) )	//["say", "speak", "fun"]
console.log( Object.getOwnPropertyNames(Demo.prototype) )//["constructor", "say", "speak", "fun"]

其中,参考【Javascript属性枚举的5个方法比较
Object.getOwnPropertyNames()方法返回一个数组,包含所有实例属性,无论它是否可枚举(但不包括Symbol值作为名称的属性)。
Object.keys()可以取得对象上所有可枚举的实例属性,返回值是包含所有可枚举属性的字符串数组。
利用这两种方法的差异,可以检测对象的实例属性是否可枚举

2.检测对象的属性是否可枚举:

const isEnumerable = (prop, obj) => 
(Object.getOwnPropertyNames(obj).indexOf(prop)) > -1 && (Object.keys(obj).indexOf(prop) > -1);

isEnumerable是Boolean类型,返回true表示属性可枚举,false为不可枚举

isEnumerable('say', Demo.prototype) 		//false
isEnumerable('speak', Demo.prototype) 		//false
isEnumerable('constructor', Demo.prototype) 		//false

isEnumerable('say', F.prototype) 		//true
isEnumerable('speak', F.prototype) 		//true
isEnumerable('constructor', F.prototype) 		//false

猜你喜欢

转载自blog.csdn.net/qq_35087256/article/details/83387528