JS中原型是一个很重要的概念,有点类似于java类中的静态变量,这么说也不是很准确。构造函数有个prototype属性,该属性是一个对象叫做原型对象,通过该属性可以为构造函数添加其实属性和方法然后被对象使用。
//构造函数 function User(name, age) { this.name = name; this.age = age; } //原型中添加属性 User.prototype.sex = "男"; //原型中添加方法 User.prototype.sleep = function () { console.log("睡觉~"); } var user = new User("冷艳的板栗", 20); console.dir(user); console.dir(User); console.log(user.sex);// 男 user.sleep();// 睡觉~console.dir()语句是输出结构:
可以看到实例对象user中有age,name属性,还有个User原型,User原型中有构造器constructor,还有我们指定的sex属性和sleep()方法。构造函数中prototype属性,其内容和实例对象中的User原型内容是一致的。由于我使用的是Safari浏览器实例对象中打印的是User原型,在Google浏览器中打印的应该是__proto__。
相当于通过字面量的方式创建对象。
3.原型对象中方法相互调用 User.prototype.sleep = function () { this.wash(); console.log("睡觉~") } User.prototype.wash = function () { console.log("洗刷~"); } var user = new User("冷艳的板栗", 20); user.sleep(); //洗刷~ //睡觉~在sleep方法中调用wash方法。
4.原型对象和实例对象变量方法重名问题 function User(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } //原型中添加属性 User.prototype.sex = "男"; var user = new User("冷艳的板栗", 20, "女"); console.log(user.sex);//女因此构造函数中如果存在某个变量,会使用构造函数中的变量,如果没有才会去原型中去找。
5.为内置对象添加原型方法 var array = new Array(1, 2, 3, 4, 5, 6); Array.prototype.getLast=function () { return this[this.length-1]; } console.log(array.getLast());//6为数组Array添加了一个getLast的方法。
6.原型的好处未完待续…