1.构造属性
我们创建构造函数的时候,原型对象上会有一个constructor属性,它是原型对象所独有的
function Person(name,age){this.name=name;this.age=age;}var p = new Person("cheng",20);console.log(p);console.log(p.constructor==Person);//truevar arr=[1,2,3];console.log(arr.constructor==Array);//true
2.重置构造属性
问题:我们以直接量(对象)形式,给原型对象添加属性的时候,它的constructor会指向object
解决:重置constructor属性
function Person(name,age){this.name=name;this.age=age;}Person.prototype={constructor:Person,//重置constructor属性sayName:function(){console.log(this.name);},sayAge(){console.log(this.age);}}var p=new Person("cheng",20);console.log(p.constructor)//Personconsole.log(p.constructor==Person);//trueconsole.log(p instanceof Person);//true</script>
3.私有属性和公有属性
公有属性:一般在原型对象上
私有属性:通过this关键字添加的
hasOwnProperty可以判断属性是私有的还是公有的
function Person(name,age){this.name=name;this.age=age;}Person.prototype={constructor:Person,//重置constructor属性sayName:function(){console.log(this.name);},sayAge(){console.log(this.age);}}/* 公有属性:一般在原型对象上私有属性:通过this关键字添加的hasOwnProperty可以判断属性是私有的还是公有的*/var p=new Person("cheng",20);console.log(p.hasOwnProperty("name"));//trueconsole.log(p.hasOwnProperty("sayName"));//falseconsole.log(p.hasOwnProperty(constructor));//false 构造属性不是私有的
