来个例子认识一下:函数
1 function Person() { 2 3 } 4 Person.prototype.name = '原型对象上定义的属性'; 5 Person.prototype.sayName = function () { 6 console.log('原型对象上的方法'); 7 } 8 9 var person1 = new Person(); 10 person1.sayName(); // '原型对象上的方法'
这里的 Person 就是一个构造函数,和普通的函数是同样的,只是构造函数要经过new 操做符来使用。this
Person.prototype 就是原型对象spa
而person1 就是Person的一个实例。prototype
1 Person.prototype.constructor == Person // true
1 console.log(Person.prototype.isPrototypeOf(person1)); // true
3、原型链的造成指针
1 function typeOne() { // 这就是对象1 2 this.val = true; 3 } 4 typeOne.prototype.getTypeOneVal = function(){ 5 return this.val; 6 } 7 8 function typeTwo(){ 9 this.valTwo = false; 10 } 11 typeTwo.prototype = new typeOne(); // 让对象2的原型指向对象1的实例,这时候对象2的原型上就有了对象1拥有的属性和方法 13 console.log(typeTwo.prototype.getTypeOneVal()) // true 14 15 //这时候再实例化 typeTwo 16 17 var instance = new typeTwo(); 18 console.log(instance.getTypeOneVal()) // 会在原型链上查找
这就是一个简单的原型链实现了,当出现第三个对象、第四个对象这样链式的写下去,原型链将会更长。code