您的位置:首页 > Web前端 > JavaScript

js学习笔记01

2014-09-11 10:52 260 查看
1 传值和传址:

js的数据赋值根据数据类型来判别,

传值:数据值,布尔型,字符型基本数据

传址:数据,hash对象,赋值的过程会用内存地址赋值,影响原数据。解决方案:遍历数组和对象赋值,相当于传值。

prototype也是hash对象,赋值的话也会传址.

function Animal(name){
this.name=name;
this.type="animal";
}
Animal.prototype.say=function(){
console.log(this.name+"type is:"+this.type);
}
function Bird(name){
Animal.call(this,name);
}

Bird.prototype.fly=function(){
console.log("I'm flying");

}
Bird.prototype=Animal.prototype;
var mybird=new Bird("bird");
var mydog=new Animal();

mybird.fly();//I'm flying

mydog.fly();//I'm flying
Animal的prototype也会带有fly()方法。

解决方案:

(1)上述类似的,遍历赋值

function Animal(name){
this.name=name;
this.type="animal";
}
Animal.prototype.say=function(){
console.log(this.name+"type is:"+this.type);
}
function Bird(name){
Animal.call(this,name);
}

for(var p in Animal)
{
Bird.prototype[p]=Animal.prototype[p];
}
Bird.prototype.fly=function(){
console.log("I'm flying");

}

var mybird=new Bird("bird");
var mydog=new Animal();

mybird.fly();//I'm flying

mydog.fly();// Uncaught TypeError: undefined is not a function 


(2)把bird作为Animal的一个实例

function Animal(name){
this.name=name;
this.type="animal";
}
Animal.prototype.say=function(){
console.log(this.name+"type is:"+this.type);
}
function Bird(name){
Animal.call(this,name);
}

Bird.prototype=new Animal();
Bird.prototype.constructor=Bird;
Bird.prototype.fly=function(){
console.log("I'm flying");
}

var mybird=new Bird("bird");
var mydog=new Animal();

mybird.fly();//I'm flying

mydog.fly(); // Uncaught TypeError: undefined is not a function 

(3)把方法封装起来

function extend(subClass,superClass){
var F=function(){};
F.prototype=superClass.prototype;
subClass.prototype=new F();
subClass.prototype.contructor=subClass;

}

function Animal(name){
this.name=name;
this.type="animal";
}
Animal.prototype.say=function(){
alert(this.name+"type:"+this.type);
}
function Bird(name){
this.name=name;
this.type="bird";
}
extend(Bird,Object);
Bird.prototype.fly=function(){
alert("I'm flying");
}

var canary=new Bird("xiaocui");
var animal= new Animal();
canary.say();
canary.fly();


2 数据类型

undefined,null,"",0,转换为逻辑值为false,其他(简单类型,对象,函数)都为true。在这五个之中,undefined==null为true,其实均为false;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: