首页 > 编程语言 > 详细

创建 JavaScript 类和对象 prototype

时间:2018-06-14 13:15:11      阅读:170      评论:0      收藏:0      [点我收藏+]

创建 JavaScript 对象

通过 JavaScript,您能够定义并创建自己的对象。

创建新对象有两种不同的方法:

  1. 定义并创建对象的实例(直接创建方式)
    1. person=new Object();
      person.firstname="Bill";
      person.lastname="Gates";
      person.age=56;
      person.eyecolor="blue";

      或者

    2. person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

       

  2. 使用函数来定义对象,然后创建新的对象实例      
//构造函数法创建类
//构造函数法创建类
function
person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; }
myFather=new person("Bill","Gates",56,"blue");

 

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>
<script>
function Employee(name,jobtitle,born){
    this.name=name;
    this.jobtitle=jobtitle;
    this.born=born;
}
var employee=new Employee("Fred Flintstone","Caveman",1970);
//1.在类的原型对象中进行属性扩展操作
Employee.prototype.salary=null;
employee.salary=20000;
document.write(fred.salary);

//2.在类的原型对象中进行方法扩展操作
Employee.prototype.sayHello = function () {
    alert(Hello: + this.name);
}
employee.sayHello(); // => 弹出 Hello:tom
</script>
</body>
</html>

参考:https://www.cnblogs.com/polk6/p/4492757.html

创建 JavaScript 类和对象 prototype

原文:https://www.cnblogs.com/zhaoyanhaoBlog/p/9182439.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!