创建的每一个函数,解析器都会添加一个属性prototype,称为原型。
属性prototype会指向一个原型对象普通函数调用prototype没有任何作用构造函数(类)调用prototype,通过构造函数(类)创建的对象(实例)都有一个隐含的属性__proto__,可以通过__proto__指向同一个原型对象特点:原型对象相当于一个公共的区域,所有同一个类的实例都可以访问到同一个原型对象,可以将对象中共有的内容,统一设置到原型对象中,供所有的实例访问。
作用:创建构造函数时,可以将这些对象共有的属性和方法,统一添加到原型对象prototype中,节省空间。 实例1:
<script type="text/javascript"> function Person(name,gender,age){ this.name = name; this.gender = gender; this.age = age; } //原型中添加共有方法setName Person.prototype.setName = function(){ return this.name; } //原型中添加共有属性a Person.prototype.a = 123; per1 = new Person("张三","男",18); per2 = new Person("李四","男",18); //当访问对象的一个属性或方法时,会先在自身寻找,没有则到原型对象中寻找 alert(per1.setName()); alert(per2.setName()); alert(Person.prototype == per1.__proto__); </script>检查属性是否存在,若存在,是存在于在哪里?
1、属性 in 对象
只能检查属性是否存在,无法判断具体位置。
2、hasOwnProperty
能检查出属性的具体位置。
代码接实例1:
//in alert("name" in per1); //true,只说明name属性存在 alert("a" in per1); //true,只说明a属性存在 //hasOwnProperty alert(per1.hasOwnProperty("name")); //true,说明对象本身有name属性 alert(per1.hasOwnProperty("a")); //false,说明对象本身没有属性 alert(per1.__proto__.hasOwnProperty("name")); //false,说明原型对象里没有name属性 alert(per1.__proto__.hasOwnProperty("a")); //true,说明原型对象里有该属性hasOwnProperty是对象的原型对象的原型对象里的属性(最深层)
代码接实例1:
alert(per1.__proto__.hasOwnProperty("hasOwnProperty"));//false,per1.__proto__不存在hasOwnProperty属性 alert(per1.__proto__.__proto__.hasOwnProperty("hasOwnProperty"));//true,per1.__proto__.__proto__存在hasOwnProperty属性