构造函数创建对象:
function Person() {
}
var person = new Person();
person.name = 'Kevin';
console.log(person.name) // Kevin
每个构造函数都有一个 prototype 属性
当使用 new 创建了一个实例对象 ,该对象就会从原型中继承属性
实例对象都会有一个属性叫proto,该属性会指向该对象的原型
function Person() {
}
var person = new Person();
console.log(person.__proto__ === Person.prototype); // true
每个原型都会有一个constructor属性指向关联的构造函数
function Person() {
}
console.log(Person === Person.prototype.constructor); // true
在下面这个例子中,我们给实例对象 person 添加了 name 属性,当我们打印 person.name 的时候,结果自然为 Daisy。
但是当我们删除了 person 的 name 属性时,读取 person.name,从 person 对象中找不到 name 属性就会从 person 的原型也就是 person.proto ,也就是 Person.prototype中查找,幸运的是我们找到了 name 属性,结果为 Kevin。
function Person() {
}
Person.prototype.name = 'Kevin';
var person = new Person();
person.name = 'Daisy';
console.log(person.name) // Daisy
delete person.name;
console.log(person.name) // Kevin
如何准确判断一个变量是数组类型
var arr = []
arr instanceof Array //true
typeof arr // Object typeof是无法判断是否是数组的
js继承的多种方式
- 原型链继承 缺点:引用类型的属性被所有实例共享,在创建child实例时不能向Person 传参
function Person(){
this.name = 'xiaopao';
}
Person.prototype.getName = function(){
console.log(this.name);
}
function Child(){
}
Child.prototype = new Person();
var child1 = new Child();
child1.getName(); // xiaopao
- 借用构造函数继承(经典继承)
function Person(){
this.name = 'xiaopao';
this.colors = ['red', 'blue', 'green'];
}
Person.prototype.getName = function(){
console.log(this.name);
}
function Child(){
Person.call(this);
}
var child1 = new Child();
var child2 = new Child();
child1.colors.push('yellow');
console.log(child1.name);
console.log(child1.colors); // ["red", "blue", "green", "yellow"]
console.log(child2.colors); // ["red", "blue", "green"]
优点:
1.避免了引用类型的属性被所有实例共享
2.可以在Child中向Parent传参
缺点:
1.只是子类的实例,不是父类的实例
2.方法都在构造函数中定义,每次创建实例都会创建一遍方法
- 冒充对象继承 把父类私有的和公有的克隆一份一样的给子类
function Son(){
var temp = new Father()
for(var k in temp){
this[k] = temp[k]
}
temp = null
}
var son = new Son()
console.log(son.sleep()) // father正在睡觉
console.log(son.look('TV')) // father正在看TV
- ES6 class类的继承
class Person{
constructor(name){
this.name = name;
}
showName(){
return this.name;
}
}
class SubPerson extends Person{
constructor(name,job){
super(name); // 指向父类的构造函数
this.job = job;
}
showJob(){
return this.job;
}
}
var p1 = new SubPerson('苏日俪格','前端开发');
console.log(p1.name); // 苏日俪格
// console.log(p1.showName()); // 苏日俪格
// console.log(p1.job); // 前端开发
extends就代表这继承的意思,super就是指向父类的构造函数,指代了整个prototype对象或者_proto_指针指向的对象