var obj = new fun();
1创建空白对象 2上下文this指向这个空白对象 3执行函数体语句 4return this对象
prototype
prototype属性值是个对象,它默认拥有constructor属性指回函数
function sum(a,b){
return a+b;
}
console.log(sum.prototype.constructor===sum); //true
原型链查找
实例可以打点访问它的原型的属性和方法,称为原型链查找
function People(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
People.prototype.nationality='中国';
var xiaoming=new People('小明',12,'男');
console.log(xiaoming.nationality);
console.log(xiaoming);
console.log(xiaoming.__proto__===People.prototype);
验证方法不是同一个函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function People() {
this.sayHello = function () {
};
}
var xiaoming = new People();
var xiaohong = new People();
console.log(xiaoming.sayHello === xiaohong.sayHello); //false
</script>
</body>
</html>
验证方法是同一个函数(把方法要写到原型上)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function People(name,age,sex) {
this.name=name;
this.age=age;
this.sex=sex;
}
People.prototype.sayHello=function (){
console.log('你好,我是'+this.name+'我今年'+this.age+'岁了');
}
var xiaoming = new People('小明',12,'男');
var xiaohong = new People('小红',11,'女');
console.log(xiaoming.sayHello === xiaohong.sayHello); //true
</script>
</body>
</html>
原型链的终点(Object.prototype)
People.prototype对象可以看做是Object对象new出来的对象,即是Object的实例
Object对象天生就存在Object.prototype对象,它是People.prototype对象的原型
Object.prototype.__proto__为null
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function People(name,age) {
this.name=name;
this.age=age;
}
var xiaoming = new People('小明',12);
console.log(xiaoming.__proto__.__proto__===Object.prototype); //true
console.log(Object.prototype.__proto__); //null
var char=xiaoming.toString();
console.log(char);
console.log(Object.prototype.hasOwnProperty('hasOwnProperty'));
console.log(Object.prototype.hasOwnProperty('toString'));
</script>
</body>
</html>
关于数组的原型链
继承
通过原型链实现继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.sayHello = function () {
console.log('你好,我是' + this.name + ',我今年' + this.age + '岁了');
}
function Student(name, age, sex, school) {
this.name = name;
this.age = age;
this.sex = sex;
this.school = school;
}
// 关键语句,实现继承
Student.prototype = new People();
Student.prototype.study = function () {
console.log('我在' + this.school + '读书');
}
var xiaoming = new Student('小明', 12, '男', '广州大学');
xiaoming.sayHello();
xiaoming.study();
</script>
</body>
</html>