所有JavaScript对象都从原型继承属性和方法。
10年积累的网站设计制作、成都网站设计经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先做网站后付款的网站建设流程,更有安宁免费网站建设让你可以放心的选择与我们合作。<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>js</title>
<body>
<h3>JavaScript 对象</h3>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age;
</script>
</body>
</html>
我们还了解到,您无法向现有对象构造函数添加新属性:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript对象</title>
<body>
<h3>JavaScript对象</h3>
<p>您无法向构造函数添加新属性。</p>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.nationality = "English";
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML =
"The nationality of my father is " + myFather.nationality;
</script>
</body>
</html>
要向构造函数添加新属性,必须将其添加到构造函数:
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>JavaScript对象</title>
<body>
<h3> JavaScript对象</h3>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
this.nationality = "English";
}
var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML =
"我父亲的国籍是 " + myFather.nationality + ". 我母亲的国籍是: " + myMother.nationality;
</script>
</body>
</html>
所有JavaScript对象都从原型继承属性和方法:
Object.prototype位于原型继承链的顶部:Date对象,Array对象和Person对象继承自Object.prototype。
有时,您希望向给定类型的所有现有对象添加新属性(或方法)。有时您想要向对象构造函数添加新属性(或方法)。
JavaScript prototype属性允许您向对象构造函数添加新属性:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
JavaScript prototype属性还允许您向对象构造函数添加新方法:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
更好的原型对象的文章
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
新闻名称:JavaScriptprototype原型用法-创新互联
新闻来源:https://www.cdcxhl.com/article26/dgdcjg.html
成都网站建设公司_创新互联,为您提供ChatGPT、用户体验、微信小程序、关键词优化、云服务器、定制网站
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联