javascriptは対象に向ける
2231 ワード
this 1.一般関数
function t(){
this.age=23;
console.log(this);
}
t()// null,this null js this window, es5
2.対象とする方法で呼び出します.var intro=function(){return "mynameis"+this:name}
var dog={name:"123",intro:intro}
dog.intro();
var cat={name:"789"}
cat.intro=dog.intro
cat.intro();//789
3.コンストラクタfunction cat(name){
this.name=name;
this.color=color;
}
// new , , this , {}.name=name;
var cat=new cat()//
4.callとappyでthisの指向を変えることができます. .call($,$,$);
1. this
2. , $,$,$;
.apply(obj, array[]);
5.クローズドfunction t(){
var age=23;
return function(){
console.log(age++);
}
}
var tmp=t();
var age=1000;
tmp();//
6.構造方法function Dog(name,color){
this.name=name;
this.color=color;
}
var dog=new Dog("donggua","shaoyan");
console.log(dog);
7.プライベート属性function girl(name,lover){
var nm=name;
var love=lover;
this.getlove=function(){
return love;
}
this.getname=function(){
return nm;
}
}
var girl=new girl("123","234");
console.log(girl);
console.log(girl.getlove());
8.原型継承
function cat(){
this.climb=function(){
alert("ps")
}
}
function Tiger(){
this.hunt=function(){
alert("dl");
}
}
Tiger.prototype=new cat();
var tiger=new Tiger();
tiger.hunt();
tiger.climb()
//console.log(tiger)
Tiger.prototype.song=function(){
alert("789")
}
tiger.song();
9.原型詐称function good(){
this.iq=120
this.study=function(){
console.log("gao")
}
}
function bad(){
good.call(this);
this.play=function(){
console.log("mhxy")
}
}
var good=new good();
var bad=new bad();
good.study();
bad.play();
bad.good();
10.原型コピーfunction good(){
this.iq=120
this.study=function(){
console.log("gao")
}
}
function bad(){
this.play=function(){
console.log("mhxy")
}
this.extend=function(obj){
for(var k in obj){
this[k]=obj[k];
}
}
}
var good=new good();
var bad=new bad();
bad.extend(good);
console.log(bad);
11.関数もオブジェクトです.