文章目录
在对象上创建方法
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