构造属性:我们创建构造函数的时候,原型对象上会有一个constructor属性,它是原型对象所独有的
可用来判断某对象是否为某个类的实例
<script>function Person(name,age){this.name = name;this.age = age;}var p = new Person("cheng",20);console.log(p.constructor == Person); //truevar arr = [1,2,3];console.log(arr.constructor == Array); //true</script>
问题:就是我们以直接量(对象)形式,给原型对象添加属性的时候,它的 constructor会指向Object,但没改变它是某个类的实例instanceof
<script>function Person(name,age){this.name = name;this.age = age;}/* 以字面量(对象)的形式给原型对象添加属性 */Person.prototype = {sayName:function(){console.log(this.name)},sayAge(){console.log(this.age)}}var p = new Person("cheng",20);console.log(p.constructor); // ƒ Object() { [native code] }console.log(p.constructor==Person) //falseconsole.log(p instanceof Person) //true</script>
解决方法:需要重置constructor
<script>function Person(name,age){this.name = name;this.age = age;}Person.prototype = {constructor:Person, //重置constructorsayName:function(){console.log(this.name)},sayAge(){console.log(this.age)}}var p = new Person("cheng",20);console.log(p.constructor==Person) //true</script>
公有属性:在一般的原型对象上
私有属性:通过this关键字去添加的属性
hasOwnProperty可以判断属性是私有还是公有的:true表示私有;false表示公有
<script>function Person(name,age){this.name = name;this.age = age;}Person.prototype = {constructor:Person,sayName:function(){console.log(this.name)},sayAge(){console.log(this.age)}}var p = new Person("cheng",20);console.log(p.hasOwnProperty("name")) //trueconsole.log(p.hasOwnProperty("sayName")) //false</script>
Small eg:
<script>var obj = {name:"zhang"}console.log(obj.hasOwnProperty("name")) //true</script>
