JavaScript -面向对象

在对象上创建方法
let duck = {
   
  name: "Aflac",
  numLegs: 2,
  sayName: function() {
   return "The name of this duck is " + duck.name + ".";}
};
duck.sayName();
使用 this 关键字提高代码重用性
sayName: function() {
   return "The name of this duck is " + duck.name + ".";}

let duck = {
   
  name: "Aflac",
  numLegs: 2,
  sayName: function() {
   return "The name of this duck is " + this.name + ".";}
};
this 指向的就是与这个方法有关联的 duck 对象。避免变量名发生改变而造成错误
定义构造函数

Constructors 是创建对象的函数。 函数给这个新对象定义属性和行为。 可将它们视为创建的新对象的蓝图。

function Bird() {
   
  this.name = "Albert";
  this.color = "blue";
  this.numLegs = 2;
}

构造函数函数名的首字母大写,这是为了方便我们区分构造函数( constructors)和其他非构造函数。
构造函数使用 this 关键字来给它将创建的这个对象设置新的属性。 在构造函数里面,this 指向的就是它新创建的这个对象。
构造函数定义了属性和行为就可创建对象,而不是像其他函数一样需要设置返回值。
let blueBird = new Bird();
blueBird 这个实例继承了Bird 构造函数的所有属性

> 接收参数
function Bird(name, color) {
   
  this.name = name;
  this.color = color;
  this.numLegs = 2;
}
let cardinal = new Bird("Bruce", "red");
使用 instanceof 验证对象的构造函数

instanceof 将对象与构造函数之间进行比较,根据对象是否由这个构造函数创建的返回 true 或者 false

let Bird = function(name, color) {
   
  this.name = name;
  this.color = color;
  this.numLegs = 2;
}

let crow = new Bird("Alexis", "black");
instanceof 方法会返回 true

crow instanceof Bird;
一次修改所有对象的实例 prototype

prototype 是一个可以在所有 Bird 实例之间共享的对象

Bird.prototype.numLegs = 2;
所有的 Bird 实例都新增了共同的 numLegs 属性值
可以把 prototype 看作是创建对象的 "配方"
自身属性和原型属性

自身属性是直接在对象上定义的。 而原型属性在 prototype 上定义

function Bird
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值