JavaScript prototype原型用法
程序员文章站
2022-03-23 13:39:19
JavaScript prototype原型用法,所有JavaScript对象都从原型继承属性和方法。 ......
javascript对象原型
所有javascript对象都从原型继承属性和方法。
<!doctype html> <html> <meta charset="utf-8"> <title>js</title> <body> <h2>javascript 对象</h2> <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> <h2>javascript对象</h2> <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> <h2> javascript对象</h2> <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。
* date 对象继承自 date.prototype
* array 对象继承自 array.prototype
* person 对象继承自 person.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; };
下一篇: 最全的Vue组件通信方式总结
推荐阅读
-
详解JavaScript中typeof与instanceof用法
-
JavaScript函数、闭包、原型、面向对象学习笔记
-
JavaScript内置对象math,global功能与用法实例分析
-
JavaScript中的Math.LN2属性用法详解
-
javascript回调函数的概念理解与用法分析
-
分析javascript原型及原型链
-
javascript异步处理与Jquery deferred对象用法总结
-
JavaScript中的原型prototype完全解析
-
php示例详解Constructor Prototype Pattern 原型模式
-
JavaScript中的prototype原型学习指南