构造函数内部原理
1.在函数体最前面隐私的加上this={}
2.执行this.xxx=xxx
3.隐式的返回this
// 注意:构造函数要用大驼峰命名
function Constructor(name,sex) {
this.name = name;
this.sex = sex;
}
let msg = new Constructor('XYZ',22);
let msg1 = new Constructor('LM',21);
console.log(msg);
console.log(msg1);
原型讲解
//Constructor.prototype --原型
//Constructor.prototype={} 是祖先
Constructor.prototype.surname = 'xie';
function Constructor() {
}
let msg = new Constructor();
console.log(msg.surname);//xie
原型简单写法:
//原型简单写法
Constructor.prototype = {
profession: '前度开发',
tool: '计算机',
};
function Constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age
}
let msg = new Constructor('xyz', '男', 22);
console.log(msg);
原型运用:提取公共部分
Constructor.prototype.profession = '前端开发';
Constructor.prototype.tool = '计算机';
function Constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age
}
let msg = new Constructor('xyz', '男', 22);
let msg1 = new Constructor('lm', '女', 21);
console.log(msg);
console.log(msg1);
原型运用:修改原型里面的信息
Constructor.prototype.profession = '前度开发';
Constructor.prototype.tool = '计算机';
function Constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age
}
let msg = new Constructor('xyz', '男', 22);
//修改原型里面的信息
Constructor.prototype.profession = 'WEB前度开发工程师';
console.log(msg);
原型运用:删除属性
Constructor.prototype.profession = '前度开发';
Constructor.prototype.tool = '计算机';
function Constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age
}
let msg = new Constructor('xyz', '男', 22);
//删除属性
delete msg.name;
//现在我想删除原型里面的属性,这个时候计算机会给你返回true,其实并没有删除掉
delete msg.profession;
console.log(msg);
查看对象的构造函数(简单点就是说,现在msg不知道是谁生的它,它想找到它的爸爸)
function Constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age
}
let msg = new Constructor('xyz', '男', 22);
//现在我想查看对象的构造函数(简单点就是说,现在msg不知道是谁生的它,它想找到它的爸爸)
console.log(msg.constructor);