User Tools

Site Tools


ui:javascript-prototype

Javascript - Prototype

每个函数都有一个原型对象属性,对象没有原型对象属性。

function Bird(){  
}  
var bird = new Bird();  
alert(Bird.prototype); // [object Object]  
alert(bird.prototype); // undefined

使用prototype实现继承:

function Animal(){  
  this.color = "red";  
}     
function Bird(){   
  this.name="小鸟";  
}  
 
var b = new Bird();  
alert(b.color); // undefined  
 
Bird.prototype = new Animal();  
var b_ = new Bird();  
alert(b_.color); // red

使用prototype扩展现有系统函数:

在javascript中Array有个push()方法,可以向数组中添加新的元素,数组是有序且可以重复的,有时候需要数组中的元素不重复(如果数组中存放的是对象,对象的比较需要自己实现),这时候可以使用prototype扩张现有的数组的方法。

Array.prototype.pushEx = function(obj){  
  var a = true;  
  for (var i = 0; i < this.length; i++) {  
    if (this[i]== obj) {  
       this[i] = obj;  
       a =false;  
       break;  
    }  
  }  
  if(a){  
    this.push(obj);   
  }  
  return this.length;  
}  
var test1 = new Array();  
test1.pushEx("bb");  
test1.pushEx("bb");  
test1.pushEx("dd");  
alert(test1) //bb,dd 

Javascript - Prototype2

  • JavaScript 是基于对象的,任何元素都可以看成对象。然而,类型和对象是不同的。本文中,我们除了讨论类型和对象的一些特点之外,更重要的是研究如何写出好的并且利于重用的类型。毕竟,JavaScript这种流行的脚本语言如果能够进行良好的封装,并形成一个庞大的类型库,对于重用是非常有意义的。
  • 网上对于prototype的文章很多,一直没明白核心的思想。最后写了很多例子代码后才明白:prototype只能用在类型上。
  • 以下是一些关于类型和对象的例子,大家看完例子后可能更容易理解类型和对象之间的联系:
ui/javascript-prototype.txt · Last modified: 2018/07/24 08:13 by 127.0.0.1

Except where otherwise noted, content on this wiki is licensed under the following license: 沪ICP备12046235号-2
Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki