JavaScript prototype原型用法

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


    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;

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


    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;

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


    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;

原型继承
所有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;
};

更好的原型对象的文章

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69942367/viewspace-2651817/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/69942367/viewspace-2651817/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值