JS中的prototype详解

原文1:

本文基于下面几个知识点:

 

1 原型法设计模式

在.Net中可以使用clone()来实现原型法

原型法的主要思想是,现在有1个类A,我想要创建一个类B,这个类是以A为原型的,并且能进行扩展。我们称B的原型为A。

 

2 javascript的方法可以分为三类:

a 类方法

b 对象方法

c 原型方法

例子:

复制代码
function  People(name)
{
  this .name = name;
  // 对象方法
  this .Introduce = function (){
    alert(
" My name is  " + this .name);
  }
}
// 类方法
People.Run = function (){
  alert(
" I can run " );
}
// 原型方法
People.prototype.IntroduceChinese = function (){
  alert(
" 我的名字是 " + this .name);
}

 

// 测试

var  p1 = new  People( " Windking " );

p1.Introduce();

People.Run();

p1.IntroduceChinese();
复制代码

 

3 obj1.func.call(obj)方法

意思是将obj看成obj1,调用func方法

 

 

好了,下面一个一个问题解决:

 

prototype是什么含义?

 

javascript中的每个对象都有prototype属性,Javascript中对象的prototype属性的解释是:返回对象类型原型的引用。

A.prototype = new B();

理解prototype不应把它和继承混淆。A的prototype为B的一个实例,可以理解A将B中的方法和属性全部克隆了一遍。A能使用B的方法和属性。这里强调的是克隆而不是继承。可以出现这种情况:A的prototype是B的实例,同时B的prototype也是A的实例。

 

先看一个实验的例子:


复制代码
function  baseClass()
{
  this .showMsg  =   function ()
  {
     alert(
" baseClass::showMsg " );   
  }
}

function  extendClass()
{
}

extendClass.prototype 
=   new  baseClass();
var instance 
=   new  extendClass();
instance.showMsg(); 
//  显示baseClass::showMsg
复制代码

我们首先定义了baseClass类,然后我们要定义extentClass,但是我们打算以baseClass的一个实例为原型,来克隆的extendClass也同时包含showMsg这个对象方法。

extendClass.prototype = new baseClass()就可以阅读为:extendClass是以baseClass的一个实例为原型克隆创建的。

 

那么就会有一个问题,如果extendClass中本身包含有一个与baseClass的方法同名的方法会怎么样?

下面是扩展实验2:


复制代码
function  baseClass()
{
    
this .showMsg  =   function ()
    {
        alert(
" baseClass::showMsg " );   
    }
}

function  extendClass()
{
    
this .showMsg  = function  ()
    {
        alert(
" extendClass::showMsg " );
    }
}

extendClass.prototype 
=   new  baseClass();
var instance 
=   new  extendClass();

instance.showMsg();
// 显示extendClass::showMsg
复制代码

 

实验证明:函数运行时会先去本体的函数中去找,如果找到则运行,找不到则去prototype中寻找函数。或者可以理解为prototype不会克隆同名函数。

 

那么又会有一个新的问题:

如果我想使用extendClass的一个实例instance调用baseClass的对象方法showMsg怎么办?

 

答案是可以使用call:


复制代码
extendClass.prototype  =   new  baseClass();
var instance 
=   new  extendClass();


var  baseinstance  =   new  baseClass();
baseinstance.showMsg.call(instance);
// 显示baseClass::showMsg
复制代码

 

这里的baseinstance.showMsg.call(instance);阅读为“将instance当做baseinstance来调用,调用它的对象方法showMsg”

好了,这里可能有人会问,为什么不用baseClass.showMsg.call(instance);

这就是对象方法和类方法的区别,我们想调用的是baseClass的对象方法

 

最后,下面这个代码如果理解清晰,那么这篇文章说的就已经理解了:

 


复制代码
< script type = " text/javascript " >

function  baseClass()
{
    
this .showMsg  =   function ()
    {
        alert(
" baseClass::showMsg " );   
    }
   
    
this .baseShowMsg  =   function ()
    {
        alert(
" baseClass::baseShowMsg " );
    }
}
baseClass.showMsg 
=   function ()
{
    alert(
" baseClass::showMsg static " );
}

function  extendClass()
{
    
this .showMsg  = function  ()
    {
        alert(
" extendClass::showMsg " );
    }
}
extendClass.showMsg 
=   function ()
{
    alert(
" extendClass::showMsg static " )
}

extendClass.prototype 
=   new  baseClass();
var instance 
=   new  extendClass();

instance.showMsg(); 
// 显示extendClass::showMsg
instance.baseShowMsg();  // 显示baseClass::baseShowMsg
instance.showMsg();  // 显示extendClass::showMsg

baseClass.showMsg.call(instance);
// 显示baseClass::showMsg static

var  baseinstance  =   new  baseClass();
baseinstance.showMsg.call(instance);
// 显示baseClass::showMsg

< / script>

出处:(http://www.cnblogs.com/yjf512/



原文2:

函数:原型

每一个构造函数都有一个属性叫做原型(prototype,下面都不再翻译,使用其原文)。这个属性非常有用:为一个特定类声明通用的变量或者函数。

prototype的定义

你不需要显式地声明一个prototype属性,因为在每一个构造函数中都有它的存在。你可以看看下面的例子:

Example PT1

CODE:
function Test()
{
}
alert(Test.prototype); // 输出 "Object"

给prototype添加属性

就如你在上面所看到的,prototype是一个对象,因此,你能够给它添加属性。你添加给prototype的属性将会成为使用这个构造函数创建的对象的通用属性。

例如,我下面有一个数据类型Fish,我想让所有的鱼都有这些属性:livesIn="water"和price=20;为了实现这个,我可以给构造函数Fish的prototype添加那些属性。

Example PT2

CODE:
function Fish(name,color)
{
this.name=name;
this.color=color;
}
Fish.prototype.livesIn="water";
Fish.prototype.price=20;

接下来让我们作几条鱼:

CODE:
var fish1=newFish("mackarel", "gray");
var fish2=new Fish("goldfish", "orange");
var fish3=new Fish("salmon", "white");

再来看看鱼都有哪些属性:

CODE:
for (int i=1;i<=3; i++)
{
var fish=eval_r("fish"+i);   //我只是取得指向这条鱼的指针
alert(fish.name+","+fish.color+","+fish.livesIn+","+fish.price);
}

输出应该是:

CODE:
"mackarel, gray, water,20"
"goldfish, orange, water, 20"
"salmon, white water, 20"

你看到所有的鱼都有属性livesIn和price,我们甚至都没有为每一条不同的鱼特别声明这些属性。这时因为当一个对象被创建时,这个构造函数将会把它的属性prototype赋给新对象的内部属性__proto__。这个__proto__被这个对象用来查找它的属性。

你也可以通过prototype来给所有对象添加共用的函数。这有一个好处:你不需要每次在构造一个对象的时候创建并初始化这个函数。为了解释这一点,让我们重新来看ExampleDT9并使用prototype来重写它:

用prototype给对象添加函数

Example PT3

CODE:

function Employee(name, salary)
{
this.name=name;               
this.salary=salary;
}
Employee.prototype.getSalary=function getSalaryFunction()
{
return this.salary;
}

Employee.prototype.addSalary=functionaddSalaryFunction(addition)
{
this.salary=this.salary+addition;
}

 

我们可以象通常那样创建对象:

CODE:
var boss1=newEmployee("Joan", 200000);
var boss2=new Employee("Kim", 100000);
var boss3=new Employee("Sam", 150000);

并验证它:

CODE:
alert(boss1.getSalary());  // 输出 200000
alert(boss2.getSalary());   // 输出100000
alert(boss3.getSalary());   // 输出150000

这里有一个图示来说明prototype是如何工作的。这个对象的每一个实例(boss1, boss2,boss3)都有一个内部属性叫做__proto__,这个属性指向了它的构造器(Employee)的属性prototype。当你执行getSalary或者addSalary的时候,这个对象会在它的__proto__找到并执行这个代码。注意这点:这里并没有代码的复制(和Example DT8的图表作一下对比)。


地址:http://blog.sina.com.cn/s/blog_7045cb9e0100rtoh.html


原文3:

JavaScript中__proto__与prototype的关系

这里讨论下对象的内部原型(__proto__)和构造器的原型(prototype)的关系。

 

一、所有构造器/函数的__proto__都指向Function.prototype,它是一个空函数(Empty function)

1
2
3
4
5
6
7
8
9
Number.__proto__ === Function.prototype  // true
Boolean.__proto__ === Function.prototype // true
String.__proto__ === Function.prototype  // true
Object.__proto__ === Function.prototype  // true
Function.__proto__ === Function.prototype // true
Array.__proto__ === Function.prototype   // true
RegExp.__proto__ === Function.prototype  // true
Error.__proto__ === Function.prototype   // true
Date.__proto__ === Function.prototype    // true

 

JavaScript中有内置(build-in)构造器/对象共计12个(ES5中新加了JSON),这里列举了可访问的8个构造器。剩下如Global不能直接访问,Arguments仅在函数调用时由JS引擎创建,Math,JSON是以对象形式存在的,无需new。它们的__proto__是Object.prototype。如下

1
2
Math.__proto__ === Object.prototype  // true
JSON.__proto__ === Object.prototype  // true

 

上面说的“所有构造器/函数”当然包括自定义的。如下

1
2
3
4
5
6
// 函数声明
function Person() {}
// 函数表达式
var Man = function () {}
console.log(Person.__proto__ === Function.prototype) // true
console.log(Man.__proto__ === Function.prototype)    // true

 

这说明什么呢?

所有的构造器都来自于Function.prototype,甚至包括根构造器Object及Function自身。所有构造器都继承了Function.prototype的属性及方法。如length、call、apply、bind(ES5)。

 

Function.prototype也是唯一一个typeof XXX.prototype为 “function”的prototype。其它的构造器的prototype都是一个对象。如下

1
2
3
4
5
6
7
8
9
10
console.log( typeof Function.prototype) // function
console.log( typeof Object.prototype)   // object
console.log( typeof Number.prototype)   // object
console.log( typeof Boolean.prototype)  // object
console.log( typeof String.prototype)   // object
console.log( typeof Array.prototype)    // object
console.log( typeof RegExp.prototype)   // object
console.log( typeof Error.prototype)    // object
console.log( typeof Date.prototype)     // object
console.log( typeof Object.prototype)   // object

  

噢,上面还提到它是一个空的函数,alert(Function.prototype) 下看看。

 

知道了所有构造器(含内置及自定义)的__proto__都是Function.prototype,那Function.prototype的__proto__是谁呢?

 

相信都听说过JavaScript中函数也是一等公民,那从哪能体现呢?如下

1
console.log(Function.prototype.__proto__ === Object.prototype) // true

这说明所有的构造器也都是一个普通JS对象,可以给构造器添加/删除属性等。同时它也继承了Object.prototype上的所有方法:toString、valueOf、hasOwnProperty等。

 

最后Object.prototype的__proto__是谁?

1
Object.prototype.__proto__ === null  // true

已经到顶了,为null。

 

二、所有对象的__proto__都指向其构造器的prototype

上面测试了所有内置构造器及自定义构造器的__proto__,下面再看看所有这些构造器的实例对象的__proto__指向谁?

 

先看看JavaScript引擎内置构造器

1
2
3
4
5
6
7
8
9
10
11
var obj = {name: 'jack' }
var arr = [1,2,3]
var reg = /hello/g
var date = new Date
var err = new Error( 'exception' )
 
console.log(obj.__proto__ === Object.prototype) // true
console.log(arr.__proto__ === Array.prototype)  // true
console.log(reg.__proto__ === RegExp.prototype) // true
console.log(date.__proto__ === Date.prototype)  // true
console.log(err.__proto__ === Error.prototype)  // true

 

再看看自定义的构造器,这里定义了一个Person

1
2
3
4
5
function Person(name) {
     this .name = name
}
var p = new Person( 'jack' )
console.log(p.__proto__ === Person.prototype) // true

p是Person的实例对象,p的内部原型总是指向其构造器Person的prototype。

 

每个对象都有一个constructor属性,可以获取它的构造器,因此以下打印结果也是恒等的

1
2
3
4
5
function Person(name) {
     this .name = name
}
var p = new Person( 'jack' )
console.log(p.__proto__ === p.constructor.prototype) // true

 

上面的Person没有给其原型添加属性或方法,这里给其原型添加一个getName方法

1
2
3
4
5
6
7
8
function Person(name) {
     this .name = name
}
// 修改原型
Person.prototype.getName = function () {}
var p = new Person( 'jack' )
console.log(p.__proto__ === Person.prototype) // true
console.log(p.__proto__ === p.constructor.prototype) // true

可以看到p.__proto__与Person.prototype,p.constructor.prototype都是恒等的,即都指向同一个对象。

 

如果换一种方式设置原型,结果就有些不同了

1
2
3
4
5
6
7
8
9
10
function Person(name) {
     this .name = name
}
// 重写原型
Person.prototype = {
     getName: function () {}
}
var p = new Person( 'jack' )
console.log(p.__proto__ === Person.prototype) // true
console.log(p.__proto__ === p.constructor.prototype) // false

这里直接重写了Person.prototype(注意:上一个示例是修改原型)。输出结果可以看出p.__proto__仍然指向的是Person.prototype,而不是p.constructor.prototype。

这也很好理解,给Person.prototype赋值的是一个对象直接量{getName: function(){}},使用对象直接量方式定义的对象其构造器(constructor)指向的是根构造器Object,Object.prototype是一个空对象{},{}自然与{getName: function(){}}不等。如下

1
2
3
4
var p = {}
console.log(Object.prototype) // 为一个空的对象{}
console.log(p.constructor === Object) // 对象直接量方式定义的对象其constructor为Object
console.log(p.constructor.prototype === Object.prototype) // 为true,不解释 

 

上面代码中用到的__proto__目前在IE6/7/8/9中都不支持。IE9中可以使用Object.getPrototypeOf(ES5)获取对象的内部原型。

1
2
3
var p = {}
var __proto__ = Object.getPrototypeOf(p)
console.log(__proto__ === Object.prototype) // true


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值