国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JavaScript中的prototype和constructor簡明總結(jié)

2019-11-20 20:51:40
字體:
供稿:網(wǎng)友

一、constructor
constructor的值是一個(gè)函數(shù)。在JavaScript中,除了null和undefined外的類型的值、數(shù)組、函數(shù)以及對象,都有一個(gè)constructor屬性,constructor屬性的值是這個(gè)值、數(shù)組、函數(shù)或者對象的構(gòu)造函數(shù)。如:

復(fù)制代碼 代碼如下:
var a = 12, // 數(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ù),如:

復(fù)制代碼 代碼如下:

function A(name) {
    this.name = name;
}

var a = new A('a');

console.log(a.constructor); // A(name)

調(diào)用構(gòu)造函數(shù)時(shí),需要用new關(guān)鍵字,構(gòu)造函數(shù)返回的是一個(gè)對象,看下面的代碼就知道了:

復(fù)制代碼 代碼如下:
var a = 4;
var b = new Number(4);

console.log('a: ', typeof a); // a: number
console.log('b: ', typeof b); // b: object

二、 prototype
prototype是函數(shù)的一個(gè)屬性,默認(rèn)情況下,一個(gè)函數(shù)的prototype屬性的值是一個(gè)與函數(shù)同名的空對象,匿名函數(shù)的prototype屬性名為Object。如:

復(fù)制代碼 代碼如下:
function fn() {}

console.log(fn.prototype); // fn { }

prototype屬性主要用來實(shí)現(xiàn)JavaScript中的繼承,如:

復(fù)制代碼 代碼如下:
function A(name) {
    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

這兒有一個(gè)問題,test的構(gòu)造函數(shù)其實(shí)是A函數(shù)而不是B函數(shù):

復(fù)制代碼 代碼如下:
console.log(test.constructor); // A(name)


這是因?yàn)锽.prototype = A.prototype把B.prototype的構(gòu)造函數(shù)改成了A,所以需要還原B.prototype的構(gòu)造函數(shù):
復(fù)制代碼 代碼如下:
function A(name) {
    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)

之所以要這么做,是因?yàn)閜rototype的值是一個(gè)對象,且它的構(gòu)造函數(shù)也就是它的constructor屬性的值就是它所在的函數(shù),即:

復(fù)制代碼 代碼如下:
console.log(A.prototype.constructor === A); // true

發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 青岛市| 上杭县| 聊城市| 肃南| 全南县| 华阴市| 新和县| 北安市| 潜江市| 资阳市| 和硕县| 酉阳| 册亨县| 天台县| 云浮市| 木里| 延长县| 山阴县| 年辖:市辖区| 普格县| 广元市| 万宁市| 同德县| 巴林右旗| 监利县| 绿春县| 股票| 平安县| 介休市| 彭山县| 延边| 平谷区| 罗甸县| 甘泉县| 佛坪县| 博兴县| 志丹县| 高陵县| 淳化县| 古丈县| 平潭县|