码迷,mamicode.com
首页 > 编程语言 > 详细

创建 JavaScript 类和对象 prototype

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

标签:bsp   教程   hello   创建   www.   title   方法   函数   构造   

创建 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

标签:bsp   教程   hello   创建   www.   title   方法   函数   构造   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!