JavaScript prototype原型用法

发布时间:2020-07-05 08:52:10 作者:web全栈
来源:网络 阅读:349

JavaScript对象原型

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

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

更好的原型对象的文章

推荐阅读:
  1. javascript原型和原型链
  2. Javascript对象原型Prototype的用法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js htm5 css3

上一篇:prometheus05-grafana

下一篇:了解CSS3的all属性

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》