这几个方法在js的高级编程中经常用到,对于新手来说可能还不知道他们有什么区别,我把我的体会总结下来,供大家参考:

首先,定义一个对象:

  function Parent() {this.name = "wenbo";}
Parent.prototype.alertP = function() {
alert("Parent");
} function Child() {this.age = 23;}
Child.prototype.alertC = function() {
alert("Child");
} function F() {}
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
var child = new Child();

1,instanceof()   vs   isPrototypeOf():

instanceof:判断该对象是否为另一个对象的实例。

  console.log(child instanceof  Parent); //true
console.log(child instanceof Child); //true

isPrototypeOf:判断一个对象象是否为一个实例的原型。

 Parent.prototype.isPrototypeOf(child);//true
Child.prototype.isPrototypeOf(child);//true

2, hasOwnProperty()   vs  propertyIsEnumerable():

hasOwnProperty:判断对象是否有某个特定的属性,(注意说的是对象的属性,而不是对象原型的属性)必须用字符串指定该属性。

 Parent.hasOwnProperty("name");//true
Child.hasOwnProperty("age");//true
Parent.hasOwnProperty("alertP");//false
Child.hasOwnProperty("alertC");//false

propertyIsEnumerable:判断给定的属性是否可以用 for...in 语句进行枚举。由于 for ... in 枚举是包含原型链上的属性的,但propertyIsEnumerable作用于原型方法上时,始终是返回false的,你可以这么认为,for...in可以枚举对象本身的属性和原型上的属性,而propertyIsEnumerable只能判断本身的属性是否可以枚举。此外,预定义的属性不是可列举的,而用户定义的属性总是可列举的。所以如果你只想遍历对象本身的属性,可以:

 for (var key in obj) {
if (obj.hasOwnProperty(key) {
//do something
}
}

开心一刻:

最新文章

  1. Hawk 4.4 执行器
  2. 让Visual Studio Code对jQuery支持智能提示!
  3. GA算法-R语言实现
  4. Localizing WPF with .resx files
  5. linux-i386(ubuntu)下编译安装gsoap_2.8.17过程记录
  6. MAC下编译FFMPEG
  7. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件
  8. Css实现透明效果,兼容IE8
  9. 【Java】对服务器程序的理解
  10. q3 bsp随笔(2)
  11. meta便签的用法
  12. 编写带参数decorator
  13. php 简易验证码(GD库)
  14. Android SVN开发实战的文件夹结构呈现
  15. C语言中处理结构体的原理
  16. Jenkins Installing and migration
  17. 三种不同类型的ssh隧道
  18. 两道面试题,带你解析Java类加载机制
  19. jenkins 多用户同时触发构建—简单实用
  20. springcloud9----feign-client-without-hystrix

热门文章

  1. 浅谈Eclipse调用Tomcat服务的原理
  2. stm32寄存器版学习笔记09 IIC
  3. POJ1733 Parity game 【带权并查集】*
  4. 20179223《Linux内核原理与分析》第七周学习笔记
  5. node 升级
  6. Ubuntu 破解密码及用户管理
  7. java.lang.NoSuchFieldError: TRACE
  8. spring加载bean报错:expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
  9. sqlserver2008事务日志已满
  10. ssdb的golang驱动的同步问题