<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>对象原型</title>
</head>
<body>
<script type="text/javascript">
function Animal(name) {
this.name = name;
}
// 构造函数首字母必须大写
var dog = new Animal("雷");
console.log(dog.name);
// Animal.prototype -> Object
console.log(Animal.prototype);
// 对象原型 可以为对象进行扩展
Animal.prototype.fly = function() {
console.log("飞起来了");
}
var bird = new Animal("汤");
bird.fly();
function Person() {
this.age = 20;
}
Person.prototype = Animal.prototype;
var per = new Person();
per.fly();
Person.prototype = bird;
var per1 = new Person();
console.log(per1.name);
delete per1.name;
// for in循环可以遍历对象里所有的属性和方法
for(prop in per1) {
// console.log(prop);
// 通过object.hasOwnProperty(prop)可以知道属性是本身的还是来自对象原型
if(per1.hasOwnProperty(prop)) {
console.log(prop);
// 删除本身的属性,不能删除对象原型的
delete prop;
}
}
var per2 = new Person();
console.log(per1.age);
console.log(per2.__proto__);
// 基本数据类型:number string boolean null undefined
// 其余都是对象类型:Array,RegExp...
// 区别:对象类型所有的值都是可变的,字符串是不可变的,所以不是对象类型
/*
var reg = /\b/g;
var reg = new RegExp();
var arr = [];
var arr = new Array();
per.name = "2";
var str = "sadasd";
var str2 = str.substr(0,2);
var str = new String();
*/
</script>
</body>
</html>