面向对象(二)
2018-04-03 本文已影响0人
Clayten
1.构造函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
//构造函数构建对象
//在new 构造函数时系统帮你做了两件事:1、创建了Object2、把Object返回
function Person (name,age) {
this.name = name;
this.age = age;
this.say = function () {
console.log(this.name + " is speaking");
};
}
var p1 = new Person("Tom",20);
console.log(p1.name,p1.age);
p1.say();
</script>
</body>
</html>
运行结果
HTML3.png
2.判断对象的分类
console.log(p1 instanceof Person);//true
3.将方法绑定到对象原型上
Pereson.prototype.walk=function () {
console.log(this.name + " is walk");
}
prototype:我们创建的每个函数都有夜歌原型(属性),这个属性是一个对象,它的用途是包含可以由特定类型的所有实例共享的属性和方法
4.字面量的方式创建爱你对象
var student = {}
student.name = "Lucy";
student.age = 40;
json格式造对象
var student = {
name :"Lucy",
age : 40,
walk : function () {}
}