使用构造函数的 prototype 属性来指定那些应该共享的属性和方法。组合使用构造
函数模式和原型模式时,使用构造函数定义实例属性,而使用原型定义共享的属性和方法。浏览器
function Person(){ } Person.prototype.name = "Nicholas"; Person.prototype.age = 29; Person.prototype.job = "Software Engineer"; Person.prototype.sayName = function(){ alert(this.name); }; var person1 = new Person(); person1.sayName(); //"Nicholas" var person2 = new Person(); person2.sayName(); //"Nicholas" alert(person1.sayName == person2.sayName); //true
实例(指针)->构造函数constructor属性->prototype属性->原型对象函数
方法返回 [[Prototype]] 的值。this
alert(Object.getPrototypeOf(person1) == Person.prototype); //true alert(Object.getPrototypeOf(person1).name); //"Nicholas"
function Person(){ } Person.prototype.name = "Nicholas"; Person.prototype.age = 29; Person.prototype.job = "Software Engineer"; Person.prototype.sayName = function(){ alert(this.name); }; var person1 = new Person(); var person2 = new Person(); person1.name = "Greg"; alert(person1.name); //"Greg"——来自实例 alert(person2.name); //"Nicholas"——来自原型 delete person1.name; alert(person1.name); //"Nicholas" ——
function Person() { } Person.prototype.name = "Nicholas"; Person.prototype.age = 29; Person.prototype.job = "Software Engineer"; Person.prototype.sayName = function () { alert(this.name); }; var person1 = new Person(); var person2 = new Person(); alert(person1.hasOwnProperty("name")); //false person1.name = "Greg"; alert(person1.name); //"Greg"——来自实例 alert(person1.hasOwnProperty("name")); //true alert(person2.name); //"Nicholas"——来自原型 alert(person2.hasOwnProperty("name")); //false delete person1.name; alert(person1.name); //"Nicholas"——来自原型 alert(person1.hasOwnProperty("name")); //false
使用 in 操做符, in 操做符会在经过对象可以访问给定属性时返回 true ,不管该属性存在于实例中仍是原型中。prototype
结合使用in和hasPrototypeProperty()能够肯定属性究竟是存在对象中仍是原型中指针
function hasPrototypeProperty(object, name){ return !object.hasOwnProperty(name) && (name in object); }
为减小没必要要的输入,也为了从视觉上更好地封装原型的功能,更常见的作法是用一个包含全部属性和方法的对象字面量来重写整个原型对象.code
function Person() { } Person.prototype = { name: "Nicholas", age: 29, job: "Software Engineer", sayName: function () { alert(this.name); } }; // 重设构造函数,只适用于 ECMAScript 5 兼容的浏览器 Object.defineProperty(Person.prototype, "constructor", { enumerable: false, value: Person });
因为在原型中查找值的过程是一次搜索,所以咱们对原型对象所作的任何修改都可以当即从实例上反映出来——即便是先建立了实例后修改原型也照样如此。(可是重写整个原型是不行的,由于切断了构造函数与最初原型的联系)对象
var friend = new Person(); Person.prototype.sayHi = function(){ alert("hi"); }; friend.sayHi(); //"hi"(没有问题!)