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

首頁 > 編程 > JavaScript > 正文

淺談javascript中的constructor

2019-11-20 09:45:00
字體:
來源:轉載
供稿:網友

constructor,構造函數,對這個名字,我們都不陌生,constructor始終指向創建當前對象的構造函數。

這里有一點需要注意的是,每個函數都有一個prototype屬性,這個prototype的constructor指向這個函數,這個時候我們修改這個函數的prototype時,就發生了意外。如

function Person(name,age){  this.name = name;  this.age = age;}Person.prototype.getAge = function(){  return this.age;}Person.prototype.getName = function(){  return this.name;}var p = new Person("Nicholas",18);console.log(p.constructor); //Person(name, age)console.log(p.getAge()); //18console.log(p.getName()); //Nicholas

但是如果是這樣:

function Person(name,age){  this.name = name;  this.age = age;}Person.prototype = {  getName:function(){    return this.name;  },  getAge:function(){    return this.age;  }}var p = new Person("Nicholas",18);console.log(p.constructor); //Object()console.log(p.getAge()); //18console.log(p.getName()); //Nicholas

結果constructor變了。

 原因就是prototype本身也是對象,上面的代碼等價于

Person.prototype = new Object({  getName:function(){    return this.name;  },  getAge:function(){    return this.age;  }});

因為constructor始終指向創建當前對象的構造函數,那么就不難理解上面代碼p.constructor輸出的是Object了。

對于修改了prototype之后的constructor還想讓它指向Person怎么辦呢?簡單,直接給Person.prototype.constructor賦值就可以了:

Person.prototype = {  constructor:Person,  getName:function(){    return this.name;  },  getAge:function(){    return this.age;  }}

以上這篇淺談javascript中的constructor就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 曲阳县| 云安县| 老河口市| 合江县| 开封县| 五原县| 辽源市| 荔波县| 金寨县| 南宫市| 九寨沟县| 连城县| 尤溪县| 南平市| 定远县| 阳曲县| 青州市| 永济市| 昌宁县| 乌兰浩特市| 乌海市| 饶平县| 泾源县| 华池县| 布拖县| 张家川| 青田县| 五大连池市| 美姑县| 虞城县| 新泰市| 林口县| 辉县市| 武宁县| 乌拉特前旗| 宣武区| 赣榆县| 兴隆县| 托克托县| 延长县| 孝感市|