欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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;
};