构造函数
浏览器中有内置的九个原生构造函数对象
Boolean
String
Number
Object
Function
Array
Date
RegExp
Error
构造函数与普通函数区别
- 本质上是没有区别,从语法上来讲。普通函数也可以当作构造函数来使用
- 构造函数通常会有this指定实例属性,原型对象上通常有一些公共方法
- 构造函数命名通常首字母大写 -
此例子中对需要隐藏的属性 status 和light 进行了隐藏
不能直接通过对象访问
var Car = (function{
var status = "stop";
var light = "off"
return function(type, color){
this.type = type;
this.color = color;
}
})();
Car.prototype.stop = function(){
this.stop = "stop";
this.light = "off";
console.log(this.type + "is" + this.status);
}
Car.prototype.start = function(){
this.stop ="driving";
this.light = "on";
console.log(this.type + "is" + this.status);
}
var audi = new Car("adui", "sliver");
var benz = new Car("benz", "black");
audi.start();
函数调用(this)
调用可以分为四类:
.构造函数调用模式:var adui = new Car("audi", "sliver");
.方法调用模式
.函数调用模式
.apply(call)调用模式
函数构造调用模式
如下程序
var Car = (function{
var status = "stop";
var light = "off"
return function(type, color){
this.type = type;//var audi = new Car("adui", "sliver")时 this 为audi对象
this.color = color;
}
})();
Car.prototype.stop = function(){
this.stop = "stop";
this.light = "off";
console.log(this.type + "is" + this.status);
}
Car.prototype.start = function(){
this.stop ="driving";
this.light = "on";
console.log(this.type + "is" + this.status);
}
var audi = new Car("adui", "sliver");//构造函数调用模式
注:这种调用模式中,**构造函数内部**的this对象指向被创建的调用对象,此例子中的Car构造函数中的this就指向audi这个对象
方法调用模式
概念:对象调用方法,比如本例中的audi.start();就为方法调用模式,而start()方法中的this值就为audi
var Car = (function{
var status = "stop";
var light = "off"
return function(type, color){
this.type = type;
this.color = color;
}
})();
Car.prototype.stop = function(){
this.stop = "stop";
this.light = "off";
console.log(this.type + "is" + this.status);
}
Car.prototype.start = function(){
this.stop ="driving";//audi.start()时this对象指向audi对象
this.light = "on";
console.log(this.type + "is" + this.status);
}
var audi = new Car("adui", "sliver");//构造函数调用模式
audi.start();//方法调用模式
函数调用模式
在函数内部定义的子函数,它的this对象为window对象,而不是它的上级对象
//函数调用模式
function add(i, j){
return i+j;
}