今天偶然看到一个原型的博客,看了之后还是不懂,然后就自己看书,然后看了原型函数
恩,上代码呗
<!DOCTYPE html> <html> <head> <meta charset='UTF-8'> <title>prototype</title> </head> <body> </body> <script type="text/javascript"> function person(){ } person.prototype.name='wenwen'; person.prototype.age=23; person.prototype.job='engi'; person.sayName=function(){ alert(this.name); } var person1=new person; var person2=new person; console.log(person1.name);//wenwen console.log(person2.name);//wenwen </script> </html>
这就是原型函数呢
这个也可以实例修改值
var person1=new person; var person2=new person; person1.name='hello'; console.log(person1.name);//hello console.log(person2.name);//wenwen
就是这样
然后还有个判断属性是实例属性还是原型属性的,就是hasOwnProperty()方法
var person1=new person; var person2=new person; person1.name='hello'; console.log(person1.name);//hello console.log(person2.name);//wenwen console.log(person1.hasOwnProperty('name'));//true console.log(person2.hasOwnProperty('name'));//false
而且就是delete可以删除实例属性,但是不能删除原型属性,不信看代码
var person1=new person; var person2=new person; delete person1.name; console.log(person1.name);//wenwen console.log(person2.name);//wenwen
var person1=new person; var person2=new person; person1.name='hello'; delete person1.name; console.log(person1.name);//wenwen console.log(person2.name);//wenwen
还有个in操作符咯,in操作符会通过对象能够访问给定属性时返回true,无论该属性是在实例中还是原型中,
var person1=new person; var person2=new person; person1.name='hello'; delete person1.name; console.log(person1.name);//wenwen console.log(person2.name);//wenwen console.log('name' in person1);//true
还有更简单的原型语法
person.prototype={ name:'wenwen', age:23, job:'eng', sayName:function(){ alert(this.name); } };