js基础学习(一)


学习资料来自 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 张三.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值