1. Object prototype Prototype
1.1. OVERLOAD
Constructor Create a kitten, as follows:
function Cat(name,color){ this.name = name; this.color = color;
this.run=function(){ alert ( " a ." + the this Color + " kitten flew over ..."); } this.eat=function(){ alert (this.name + " to fish "); } }
var cat1 = new Cat(); |
All of the above with this definition method, this new instance represents, will create a copy of a method when creating a new instance.
Is not it a bit redundant, how to solve ? ?
Analysis: Each type has characteristics of each instance is indeed a waste level is defined, then the general characteristics of the definition if the class level, each instance of the class automatically have enough. Here we will use the prototype .
1.2. Use prototype
1.2.1 prototype property
In JavaScript , the function itself also contains a "method" and "property" of the object. Such methods previously learned (e.g. constructor () ) and attributes ( such as name and length ) and the like.
Now to introduce a new property - prototype Prototype .
Each function we have created a prototype (prototype) property, he points to an object, and the object is to use the properties and methods that can be shared by all instances of a particular type included.
// define a constructor function Person(name,age){ } // shape function of the number of parameters console.debug(Person.length)// ==>2 // constructor console.debug(Person.constructor)// ==> Function() // prototype type console.debug(typeof Person.prototype)// ==>object // prototype content console.debug(Person.prototype)// ↓↓
|
每一个类(构造函数)都具有一个prototype属性,当创建这个类的实例对象原型对象的所有属性都被立即赋予要创建的对象中。
1.2.2. 原型操作
设值:
构造函数.原型.属性=属性值
构造函数.原型.方法=函数
取值:
对象.属性
对象.方法()
1.2.3. 属性访问的优先级
原生属性的优先级高于原型属性。遵循从上到下查找:
1.2.4. 神秘的__proto__属性
访问对象上面的属性,直接通过object.name访问。
神奇的user.__proto__属性,该属性其实就是对应User类的prototype属性。
console.debug(user.__proto__===User.prototyp);//==> true;
_proto_属性属于对象实例,prototype属性类的属性。
每个对象在创建后,都会自动建立一个到prototype上的引用,让对象具备类型原型的所有特征。
一个对象中的__proto__(prototype)属性中的成员,可以直接通过object.成员进行访问。
总结:每个类都有独立的prototype属性,向prototype对象上面添加属性,对象实例可以共享prototype对象上面的属性,如果对象本身已存在某个属性,使用对象本身上面的属性,如果没有则使用prototype上面的属性,如果是添加属性添加到对象上面,不影响对象的原型对象。
1.2.5.
扩展内置对象
1.2.5.1. 扩展Array对象
我们都知道,Array对象里没有insert(插入)和remove(删除)两个方法,都是用一个splice方法完成插入、删除等操作。
// 在指定位置插入操作 Array.prototype.insert=function(index, obj){ this.splice(index, 0, obj); }
// 在指定位置删除内容 Array.prototype.remove=function(index){ this.splice(index, 1); } |
1.2.5.2. 扩展HTMLElement对象
在新版浏览器中,所有的有DOM元素都继承于HTMLElement构造器。通过访问HTMLElement的原型,浏览器可以为我们提供扩展任意HTML节点的能力。
HTMLElement.prototype.remove = function() { if(this.parentNode){ this.parentNode.removeChild(this); } } |