文章目录
学习资料来自
https://wangdoc.com/javascript/oop/new.html
第6章:面向对象编程
6.1:实例对象与new命令
1.对象是什么?
单个物体的抽象
对象是一个容器,封装的属性和方法
6.2.构造函数
js语言的对象体系,是基于构造函数和原型链。
var Vehicle = function() {
this.price = 1000;
};
this 关键字,代表所要生成的对象实例
生成对象的时候,必须使用new命令
6.3.new 命令
new 命令就是执行构造函数,饭后一个实例对象
var Vehicle = function(p) {
this.price = p;
};
var v = new Vehicle(500);
console.log(v) //Vehicle { price: 500 }
当你不使用new,直接调用构造函数
var Vehicle = function (){
this.price = 1000;
};
var v = Vehicle();
console.log(v) // undefined
console.log(price) // 1000
变量v,直接undefined,price直接上升为全局变量。
6.4 new 命令的原理
先生成一个空对象,在空对象上进行this相关操作。
var Vehicle = function () {
this.price = 1000;
return 1000;
};
console.log((new Vehicle())) //Vehicle { price: 1000 }
var Vehicle = function (){
this.price = 1000;
return { price: 2000 };
};
console.log((new Vehicle())) //{ price: 2000 }
优先返回 对象
那如果普通函数内部没有 this 关键字,就会返回空对象。
function getMessage() {
return 'this is a message';
}
var msg = new getMessage();
console.log(msg) //getMessage {}
6.5 new.target
函数内部可以使用new.target属性。
当前调用 使用new,new.target===当前函数
如果不是,new.target,返回undefined
console.log(! undefined)
6.7 Object.create() 创建实例对象
用对象,创建出实例对象
var person1 = {
name: '张三',
age: 38,
greeting: function() {
console.log('Hi! I\'m ' + this.name + '.');
}
};
var person2 = Object.create(person1);
person2.name // 张三
person2.greeting() // Hi! I'm 张三.