创建 JavaScript 类和对象 prototype

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

猜你喜欢

转载自www.cnblogs.com/zhaoyanhaoBlog/p/9182439.html