JavaScript中的prototype和constructor簡明總結(jié)
一、constructor
constructor的值是一個函數(shù)。在JavaScript中,除了null和undefined外的類型的值、數(shù)組、函數(shù)以及對象,都有一個constructor屬性,constructor屬性的值是這個值、數(shù)組、函數(shù)或者對象的構(gòu)造函數(shù)。如:
b = 'str', // 字符串
c = false, // 布爾值
d = [1, 'd', function() { return 5; }], // 數(shù)組
e = { name: 'e' }, // 對象
f = function() { return 'function'; }; // 函數(shù)
console.log('a: ', a.constructor); // Number()
console.log('b: ', b.constructor); // String()
console.log('c: ', c.constructor); // Boolean()
console.log('d: ', d.constructor); // Array()
console.log('e: ', e.constructor); // Object()
console.log('f: ', f.constructor); // Function()
以上的構(gòu)造函數(shù)都是JavaScript內(nèi)置的,我們也可以自定義構(gòu)造函數(shù),如:
function A(name) {
this.name = name;
}
var a = new A('a');
console.log(a.constructor); // A(name)
調(diào)用構(gòu)造函數(shù)時,需要用new關(guān)鍵字,構(gòu)造函數(shù)返回的是一個對象,看下面的代碼就知道了:
var b = new Number(4);
console.log('a: ', typeof a); // a: number
console.log('b: ', typeof b); // b: object
二、 prototype
prototype是函數(shù)的一個屬性,默認(rèn)情況下,一個函數(shù)的prototype屬性的值是一個與函數(shù)同名的空對象,匿名函數(shù)的prototype屬性名為Object。如:
console.log(fn.prototype); // fn { }
prototype屬性主要用來實現(xiàn)JavaScript中的繼承,如:
this.name = name;
}
A.prototype.show = function() {
console.log(this.name);
};
function B(name) {
this.name = name;
}
B.prototype = A.prototype;
var test = new B('test');
test.show(); // test
這兒有一個問題,test的構(gòu)造函數(shù)其實是A函數(shù)而不是B函數(shù):
這是因為B.prototype = A.prototype把B.prototype的構(gòu)造函數(shù)改成了A,所以需要還原B.prototype的構(gòu)造函數(shù):
this.name = name;
}
A.prototype.show = function() {
console.log(this.name);
};
function B(name) {
this.name = name;
}
B.prototype = A.prototype;
B.prototype.constructor = B;
var test = new B('test');
test.show(); // test
console.log(test.constructor); // B(name)
之所以要這么做,是因為prototype的值是一個對象,且它的構(gòu)造函數(shù)也就是它的constructor屬性的值就是它所在的函數(shù),即:
相關(guān)文章
JavaScript基本概念初級講解論壇貼的學(xué)習(xí)記錄
JavaScript基本概念 論壇貼建議大家看下,都是一些js的高級的技巧知識小結(jié)。2009-02-02深入解析JavaScript中的數(shù)字對象與字符串對象
這篇文章主要介紹了JavaScript中的數(shù)字對象與字符串對象,是JavaScript入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-10-10Javascript入門學(xué)習(xí)第二篇 js類型
上篇文章講了js中的一些概念(詞法結(jié)構(gòu)) 和 數(shù)據(jù)類型(部分)。 這章我們 繼續(xù).然后了解下js中操作數(shù)據(jù) 和 函數(shù)的 作用域。2008-07-07document.write與writeln的輸出內(nèi)容區(qū)別說明
document.write()和document.writeln都是JavaScript向客戶端寫入的方法,writeln是以行方式輸出的,但并不是指頁面實際效果中的換行,兩種方法在查看源代碼時才看得出區(qū)別。2010-10-10javascript處理表單示例(javascript提交表單)
這篇文章主要介紹了javascript處理表單示例,處理 各種表單, 以及鏈接,按鈕的通用組件,需要的朋友可以參考下2014-04-04深入理解JavaScript系列(36):設(shè)計模式之中介者模式詳解
這篇文章主要介紹了深入理解JavaScript系列(36):設(shè)計模式之中介者模式詳解,中介者模式(Mediator)是指用一個中介對象來封裝一系列的對象交互,需要的朋友可以參考下2015-03-03