1: JavaScript的组织函数是什么?
1: 它是一个一般的函数
2: 它内部用了this关键字
3: 它有一个prototype属性,这个prototype是一个对象(固然,实在每个函数都有prototype属性)
4: 这个prototype上面是能够被继续的属性
function Apple(price, colour){
this.price = price;
this.colour = colour;
}
Apple.prototype.type = 'fruit'; //可被继续的属性
var appleRed = new Apple(10, 'red');
var appleGreen = new Apple(20, 'green');
appleRed.colour;//red
appleGreen.colour;//green
appleRed.type; //fruit
appleGreen.type;//fruit
以上是一个从原型对象(Apple)天生实例对象(appleGreen, appleRed)的例子。接下来看看基于组织函数继续:
起首假设有两个组织函数:
function Fruit(){
this.taste = 'sweet';
}
function Apple(color){
this.color = 'red'
}
我们愿望Apple能继续Fruit,怎么做?总共有5种继续要领:
1: 组织函数绑定
在子组织函数中,在父组织器身上挪用call或许apply要领
function Fruit(){
this.taste = 'sweet';
}
function Apple(color){
Fruit.apply(this, arguments);
this.color = 'red'
}
var appleRed = new Apple('red');
appleRed.taste;// 'sweet'
2: prototype赋值
实例化一个父对象,然后把它赋给子组织函数的prototype属性
function Fruit(){
this.taste = 'sweet';
}
function Apple(color){
this.color = 'red'
}
Apple.prototype = new Fruit();
Apple.prototype.constructor = Apple;//特别注意这一行
var appleRed = new Apple('red');
appleRed.taste;//'sweet'
appleRed.constructor === Apple;//true
每个实例都有一个constructor,继续自组织函数的prototype的constructor属性。在执行了
Apple.prototype = new Fruit();
以后,相称因而把Apple的prototype这个对象全部覆蓋了,这个时刻 Apple.prototype.constructor是Fruit这个要领。这模样就意味这appleRed.constructor也是Fruit,如许继续就杂沓了,由于appleRed明显是由Apple这个组织要领实例化出来的。所以我们要把Apple准确的constructor从新设置归去:
Apple.prototype.constructor = Apple;
3: 把父组织函数的prototype直接赋给子组织函数的prototype
function Fruit(){}
Fruit.prototype.taste = 'sweet';
function Apple(color){
this.color = 'red'
}
Apple.prototype = Fruit.prototype;
Apple.prototype.constructor = Apple;
var appleRed = new Apple('red');
appleRed.taste;//'sweet'
Fruit.prototype.constructor === Apple;//true
虽然完成了继续,然则如今Apple和Fruit的prototype指向了统一段内存,任何对Apple.prototype的修正都邑影响到Fruit.prototype,所以代码末了一行的这类效果,是我们不愿意看到的。
4: 应用一个空的中介组织函数
实在第四种是第二种和第三种的连系
function Fruit(){}
Fruit.prototype.taste = 'sweet';
function Apple(color){
this.color = 'red'
}
var F = function(){};
F.prototype = Fruit.prototype;
Apple.prototype = new F();
Apple.prototype.constructor = Apple;
var appleRed = new Apple('red');
appleRed.taste;//'sweet'
appleRed.constructor === Apple;//true
1: 中介组织函数的prototype=父组织函数的prototype;
2: 子组织函数的prototype=中介组织函数的一个实例;
3: 把子组织函数的constructor复原为本身
5: copy继续
就是把父组织函数的prototype上的一切属性和要领拷贝进子组织要领。
function Fruit(){}
Fruit.prototype.taste = 'sweet';
function Apple(color){
this.color = 'red'
}
function extend(child, parent){
var c = child.prototype;
var p = parent.prototype;
for(var i in p){
c[i] = p[i]
}
}
extend(Apple, Fruit);//挪用继续要领
var appleRed = new Apple('red');
appleRed.taste;//'sweet'