请选择 进入手机版 | 继续访问电脑版
开启辅助访问
帐号登录 |立即注册

如何向JS构造函数原型添加属性和方法

 
构造函数原型:
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

一、构造函数体内直接添加属性、方法
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
this.nationality = "English";//添加属性
this.name = function() {
  return this.firstName + " " + this.lastName
};//添加方法
}

二、函数外使用prototype 属性来添加
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}
Person.prototype.nationality = "English";
Person.prototype.name = function() {
  return this.firstName + " " + this.lastName
};
var myFriend = new Person("Bill", "Gates", 62, "blue");
document.getElementById("demo").innerHTML =
"My friend is " + myFriend.name();

以上就是本文的全部内容,感谢大家支持JScript之家——编程学习者社区!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

友情链接
  • 艾Q网

    提供设计文章,教程和分享聚合信息与导航工具,最新音乐,动漫,游戏资讯的网站。