JavaScript prototype原型用法

发布时间:2025-05-25 01:41:51 作者:益华网络 来源:undefined 浏览量(0) 点赞(0)
摘要:JavaScript对象原型所有JavaScript对象都从原型继承属性和方法。 functionPerson(first, last, age, eye){this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eye;}var myFather =newPerson("John","Doe",50,"blue");var myMot

JavaScript对象原型所有JavaScript对象都从原型继承属性和方法。

functionPerson(first, last, age, eye){this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eye;}var myFather =newPerson("John","Doe",50,"blue");var myMother =newPerson("Sally","Rally",48,"green"); document.getElementById("demo").innerHTML ="My father is "+ myFather.age +". My mother is "+ myMother.age;

我们还了解到,您无法向现有对象构造函数添加新属性:

functionPerson(first, last, age, eye){this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eye;}Person.nationality ="English";var myFather =newPerson("John","Doe",50,"blue");var myMother =newPerson("Sally","Rally",48,"green"); document.getElementById("demo").innerHTML ="The nationality of my father is "+ myFather.nationality;

要向构造函数添加新属性,必须将其添加到构造函数:

functionPerson(first, last, age, eye){this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eye;this.nationality ="English";}var myFather =newPerson("John","Doe",50,"blue");var myMother =newPerson("Sally","Rally",48,"green"); document.getElementById("demo").innerHTML ="我父亲的国籍是 "+ myFather.nationality +". 我母亲的国籍是: "+ myMother.nationality;

原型继承

所有JavaScript对象都从原型继承属性和方法:

Object.prototype位于原型继承链的顶部:Date对象,Array对象和Person对象继承自Object.prototype。 *Date对象继承自Date.prototype*Array对象继承自Array.prototype*Person对象继承自Person.prototype

向对象添加属性和方法

有时,您希望向给定类型的所有现有对象添加新属性(或方法)。有时您想要向对象构造函数添加新属性(或方法)。

使用原型属性

JavaScript prototype属性允许您向对象构造函数添加新属性:

functionPerson(first, last, age, eyecolor){this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eyecolor;}Person.prototype.nationality ="English";

JavaScript prototype属性还允许您向对象构造函数添加新方法:

functionPerson(first, last, age, eyecolor){this.firstName = first;this.lastName = last;this.age = age;this.eyeColor = eyecolor;}Person.prototype.name =function(){returnthis.firstName +" "+this.lastName;};

更好的原型对象的文章

二维码

扫一扫,关注我们

声明:本文由【益华网络】编辑上传发布,转载此文章须经作者同意,并请附上出处【益华网络】及本页链接。如内容、图片有任何版权问题,请联系我们进行处理。

感兴趣吗?

欢迎联系我们,我们愿意为您解答任何有关网站疑难问题!

您身边的【网站建设专家】

搜索千万次不如咨询1次

主营项目:网站建设,手机网站,响应式网站,SEO优化,小程序开发,公众号系统,软件开发等

立即咨询 15368564009
在线客服
嘿,我来帮您!