prototype原型

一、原型的基本信息

写法:构造函数.prototype.方法名=function(){}

与普通方法的区别:原型类似于css中的class,普通的方法类似于css中的style

优先级:普通方法>原型的优先级

var arr = [];
arr.number = 10;
Array.prototype.number = 20;
alert(arr.number);  //10,因为普通方法的优先级比原型高

原型方法值的比较: 运用同一个原型方法的两个对象,比较的时候值相等

var arr1=new Arrary(1,2,3);  //相当于var arr1=[1,2,3]
var arr2=new Arrary(4,5,6);
Array.prototype.sum=function(){}  //给Array都添加sum方法
alert( arr1.sum==arr2.sum );  //true,因为都是通过原型添加的,不会浪费资源,所有的对象都只有同一套函数

扩展系统对象原型:

String.prototype.trim=function(){ //去掉字符串里的空格
    return this.replace(/^\s+|\s+$/g,"");
}
var str="aaa    fff     hh"
alert( str.trim() );

 

二、写法

写法1:

面向对象的写法

function 构造函数(){

  this.属性;
}

构造函数.prototype.方法 = function(){};

面向对象的使用

var 对象1 = new 构造函数();

对象1.方法();

function CreatePerson(name) {
this.name = name;
}
CreatePerson.prototype.showName = function () {
alert(this.name);
};
var p1 = new CreatePerson('小明');
p1.showName(); //小明

写法2:

const Example = function (a, b) {
    this.a = a;
    this.b = b;
    return this;
}
Example.prototype = {
    constructor: Example,  //修改指向,具体信息参考“.constructor——查看对象的构造函数笔记”
    print: function () {  //原型下的print方法
        console.log(this.a + " " + this.b);
    }
};
const newExample = new Example("hello", "word").print();  //hello word,调用构造函数原型的print()方法

 

posted @ 2017-04-24 14:19  念念念不忘  阅读(143)  评论(0)    收藏  举报