<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script type="text/javascript"> //创建对象之原型模式 //由于由于在原型查找值的过程是一个搜索的过程,所以我们修改prototype属性。立即能够体现出来 function Person(){}; var friend = new Person(); //先创建实例 Person.prototype.sayHi = function(){ console.log('Hi'); } //后给原型添加属性 friend.sayHi(); //能够正常运行 console.log('------------------------------------'); //但是如果要是重写原型那么情况就不一样了 //当我们new一个function的时候得到实例对象 //同事创建了[[prototype]]指针指向了原型对象 //重写prototype之后,即prototype = {}之后,prototype指向了新的对象 //而实例仍然指向了原来的prototype对象 function Person(){}; var friend = new Person(); Person.prototype = { constructor: Person, name: "宝清老窖", age: 29, job: "Software", sayName: function(){ console.log(this.name); } } friend.sayName(); //error friend.sayName is not a function //所以原型的重写要注意 </script> </body> </html>
提取js
//创建对象之原型模式 //由于由于在原型查找值的过程是一个搜索的过程,所以我们修改prototype属性。立即能够体现出来 function Person(){}; var friend = new Person(); //先创建实例 Person.prototype.sayHi = function(){ console.log('Hi'); } //后给原型添加属性 friend.sayHi(); //能够正常运行 console.log('------------------------------------'); //但是如果要是重写原型那么情况就不一样了 //当我们new一个function的时候得到实例对象 //同事创建了[[prototype]]指针指向了原型对象 //重写prototype之后,即prototype = {}之后,prototype指向了新的对象 //而实例仍然指向了原来的prototype对象 function Person(){}; var friend = new Person(); Person.prototype = { constructor: Person, name: "宝清老窖", age: 29, job: "Software", sayName: function(){ console.log(this.name); } } friend.sayName(); //error friend.sayName is not a function //所以原型的重写要注意