65.9K
CodeProject 正在变化。 阅读更多。
Home

JavaScript 原型 - 基础

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.87/5 (9投票s)

2014年5月2日

CPOL

1分钟阅读

viewsIcon

19248

downloadIcon

221

原型属性允许你向对象添加属性和方法。

什么是原型?

原型属性允许你向对象添加属性和方法。

  • 原型是函数对象的一个属性。
  • 只有函数对象才能拥有原型属性。

函数

  • 是对象。
  • 返回值。
  • 可以返回对象,包括其他函数。
  • 它们有属性。
  • 它们有方法。
  • 可以被复制、删除、增强。

例如

var foo = function() { };
Console.log(foo.prototype); // Output: Object {}

什么是对象?

使用 new 关键字创建的任何内容都是一个对象

例如

new String("hi");
new Object();
new Array();
Person = function(name) { 
    this.name = name
}
Me = new Person("Imdadhusen");

对象可以使你的代码更清晰、更易于维护。它代表你的整个函数或代码块的上下文。

var timer = { start: 1000, stop: 2000 }; 

当你过一段时间后重新审视代码时,可能很难记住或映射为什么使用 2000。但是,如果你维护一个对象并说“停止”,那么你就能识别它的意义。

原型的优点

  • 鼓励模块化和可重用性
  • 提供一种一致的方式来做(不同的)事情
  • 保持代码简洁
  • 使复杂性变得简单

增强原型

向原型对象添加构造函数、属性和方法。

// instantiates an object of foo
var myfoo = new foo(); 
//Access Method of foo
console.log(myfoo.SayHello("Imdad"));  // Output "Hello Imdad!"
//Access Property of foo
console.log(myfoo.Name);  // Output "Imdad!" 
  

原型的示例

  • 字符串
  • 数字
  • 日期
  • 数组
  • 函数
    • 使用纯 JavaScript
    • 使用 jQuery

字符串

String.prototype 属性代表 String 构造函数的原型

示例

//Get File Name with Extension from Full Path
alert("C:\www\scripts\views\Utils.js".getFileName());  //Output: Utils.js
String.prototype.getFileName = function(){
     return this.match(/[^\\/]+\.[^\\/]+$/)[0];
}

alert("imdad{0}".isValidName()); //Output: false
//Username should be minimum 3 char and maximum 15 and it allowed 
//only ( .\-_$@*) special characters.
String.prototype.isValidName = function() {
     var regex = /^[a-zA-Z0-9 .\-_$@*!]{3,15}$/;
     return regex.test(this);
}

alert("imdad@yahoo.com".isValidEmail()); //Output: true
//Checking email is valid or not
String.prototype.isValidEmail = function() {
    var regex = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
    return regex.test(this);
}

数字

Number.prototype 属性代表 Number 构造函数的原型

示例

var start = 100;
var end = 200;
var value = 150;
if(value.isInRange(start,end)) //Output: 'Value is in Range'
   alert('Value is in Range');
else
    alert('Value is not in Range');

//Validate number only and within range
Number.prototype.isInRange = function(start,end){
    this.Min = start||100;
    this.Max = end||200;
    return (this.Max >= this.valueOf() && this.Min <= this.valueOf());
}

日期

Date.prototype 属性代表 Date 构造函数的原型

示例

var dt = new Date();
alert(dt.shortDate()); //Output: Fri, 2 May 14
alert(dt.fullDate());  //Output: Friday, 2 May 2014

Date.prototype.dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        Date.prototype.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

        Date.prototype.fullDay = function() {
            return this.dayNames[this.getDay()];
        };
        Date.prototype.shortDay = function() {
            return this.fullDay().slice(0, 3);
        };

        Date.prototype.fullMonth = function() {
            return this.monthNames[this.getMonth()];
        };
        Date.prototype.shortMonth = function() {
            return this.fullMonth().slice(0, 3);
        };
        Date.prototype.shortYear = function() {
            return this.getFullYear().toString().substr(2,2);
        };

        Date.prototype.shortDate = function() {
            return this.shortDay() +', '+ this.getDate() +' '+ this.shortMonth() +' '+ this.shortYear();
        }

        Date.prototype.fullDate = function() {
            return this.fullDay()  +', '+ this.getDate() +' '+ this.fullMonth() +' '+ this.getFullYear()
        }

数组

Array.prototype 属性代表 Array 构造函数的原型

示例

//Define list of users in Array for remove by index and key/pair value
var users = new Array(
                { 'Country' : 'India', 'Code' : '+91'},
                { 'Country' : 'Afghanistan', 'Code' : '+93'},
                { 'Country' : 'Bhutan', 'Code' : '+975'},
                { 'Country' : 'Brazil', 'Code' : '+55'},
                { 'Country' : 'China', 'Code' : '+86'},
                { 'Country' : 'Egypt', 'Code' : '+20'},
                { 'Country' : 'Greece', 'Code' : '+30'}
            );
users.renderList('#olUsersList'); //Render list of all users with index on order list (olUsersList)

//Remove user by Index (4) start with 0
users.removeByIndex(4);
//Refresh users list
users.renderList('#olUsersList');

//Remove user by Key (Country) and Value (Bhutan)
var key = 'Country';
var val = 'Bhutan';
users.removeByObject(key, val);
//Refresh users list
users.renderList('#olUsersList');

Array.prototype.removeByIndex = function(index) {
            this.splice(index, 1);
            return this;
        }
        Array.prototype.removeByObject = function(key, val) {
            var getUser = this.getObject(key, val);
            if(getUser !== null)
                this.splice(getUser.index, 1);
            return this;
        }
        Array.prototype.getObject = function(key, val) {
            for (var i=0; i < this.length; i++)
            {
                if (this[i][key] == val)
                    return { 'index': i , 'obj' : this[i] };
            }
            return null;
        };
        Array.prototype.renderList = function(ele) {
            $(ele).empty();
            this.forEach(function(item) {
                $(ele).append('<li>'+>('+ item.Code +')');
            });
        }
</li>'+>

使用 jQuery 的函数

使用 jQuery 我们可以扩展我们的函数对象。示例:
jQuery.fn.extend({
     setScrollbar: function(height) {
          return this.css({'overflow' : 'auto', 'height': height});
     }
});

$(document).ready(function(){
   $('#btnApplyjQueryScroll').click(function(){
       $('#dvScoll_jQuery').setScrollbar(250);
   });
});

使用纯 JavaScript 的函数

你可以使用纯 JavaScript 创建自己的自定义控件。示例:
function myScroll(ele){
    this.element = document.getElementById(ele);
}
myScroll.prototype.setScrollbar = function(height){
    this.element.style.height = height + 'px';
    this.element.style.overflow = 'auto';
}

$(document).ready(function(){
   $('#btnApplyJSScroll').click(function(){
       var t = new myScroll('dvScoll_JS');
       t.setScrollbar(150);
   });
});
我上面展示的所有示例都是针对初学者级别的开发者。他们将更清楚地了解原型对于每种数据类型的工作方式。如果你想了解更多信息,请告诉我。
© . All rights reserved.