这个问题事关js里面的很多难点的问题,诸如prototype
,call
和apply
等,也是js面向对象的问题,值得写一篇.
-
call,apply
call
和apply
还是比较高级的用法,各个地方解释不好懂,我的解释就是:
改变某个方法执行时候的this指向,就是上下文环境,如果一个函数内输出
this
为undefined
,那么,实际上,call
是没作用的,this
存在在对象里面
func.call(obj,param1,param2) //对象的参数分别写
func.apply(obj,[param1,param2]) //对象的参数写成array
例如:
var add_obj = {
a:10,
b:2
}
function sub_obj(a,b){
console.log(this.a-this.b)
}
function add(a,b){
console.log(a,b)
console.log(this)
}
function sub(a,b){
console.log(a-b)
}
//1 仅仅执行sub,因为add中的this不存在,为undefined,不改变this指向
sub.call(add,2,1)
//1 相当于上面的输出
sub.call(undefined,2,1)
//8, add_obj有this指向,sub_obj执行时候,调用add_obj的上下文环境,所以用的是add_obj的this中的a,b
sub_obj.call(add_obj ,2,1)
- 继承的实现
//父类animal
var animal = function(name,food){
this.name = name
this.food = food
this.eat = function(){
console.log("I like eating "+food)
}
this.action = function(){
console.log("I can jump and run")
}
}
//子类dog
var dog = function(name,food,praise){
//实现:将animall的this指向dog的对象,dog的this就有了animal的方法
//在class内执行,无需要实例化,变可以暴露给this
animal.call(this,name,food)
this.praise = function(){
console.log(praise)
}
}
//调用
var Dog = new dog("dog","bone","Most of us like dog")
Dog.eat() //I like eating bone
Dog.action() //I can jump and run
Dog.praise() //Most of us like dog
- prototype继承
var animal = function(name,food){
this.name = name
this.food = food
this.eat = function(){
console.log("I like eating "+food)
}
this.action = function(){
console.log("I can jump and run")
}
}
var dog = function(praise){
this.praise = function(){
console.log(praise)
}
}
//实现:其原型链指向animal的实例化对象
dog.prototype = new animal("dog","bone")
var Dog = new dog("Most of us like dog")
Dog.eat() //I like eating bone
Dog.action() //I can jump and run
Dog.praise() //Most of us like dog
- 构造函数继承
var animal = function(name,food){
this.name = name
this.food = food
this.eat = function(){
console.log("I like eating "+food)
}
this.action = function(){
console.log("I can jump and run")
}
}
var dog = function(name,food,praise){
//实现:讲animal类给dog的this对象,然后属性打开,而非实例化
this.temp = animal
this.temp(name,food)
this.praise = function(){
console.log(praise)
}
}
var Dog = new dog("dog","bone","Most of us like dog")
Dog.eat()
Dog.action()
Dog.praise()
-
面向对象
而且在用js开发时候,也可以用this
或者prototype
去进行对象化.
网友评论