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

JS对象基础 闭包等

2015-09-21 22:09 579 查看
一.我们知道js的基本数据类型包括:number,boolen,string,null及undefined;

看下面的一段代码:

  var abcobject = {

    firstname:"first",

    lastname:"last",

    sayname:function(){

      alert("i'm" + this.name);

    }

  }

//注意以上的写法,是json格式书写方式,所以每句话之间用"逗号"分割,这叫键值对;

访问的方式:

  (1).abcobject.firstname;

  (2).person["firstname"],注意前面是"firstname"才能这样做;

  (3).person["30"],注意前面是"30"才能这样用;

将person的值赋给P1,引用类型指向的是地址,访问是同块内的基本类型就是赋的值;

2.删除属性的方法:

   var Person = {

    name:"Kobe",

    age:20,

    sayname: function(){

      alert("i'm" + this.name);

    }

  }

删除属性:

  delete person.name;

    注意几个属性:

    writable:可读写性,取true或者false;

    configurable:是否能删除;

    enumerable:枚举性;

看以下的代码:

function Parent(name,age){

this.name = name;

this.age = age;

this.sayName = function(){

console.log(this.name);

}

function Child(name,age)

**this.obj = Parent;

this.obj(name,age);

delete this.obj;**

}

var c = new Child("zahngsan",22);

console.log(c.name);

//输出zhangsan;Chlid继承了Parent的属性;

除开这种call方法之外,还有apply的方法,看下面的代码:

**段的代码可以用Parent.call(this,name,age);代替;而call方法和apply方法意义相同,用法稍有不同:

function Parent(name,age){

this.name = name;

this.age = age;

this.sayName = function(){

console.log(this.name);

}

function Child(name,age)

apply(this,name,age);

}

var c = new Child("zahngsan",22);

console.log(c.name);

##2.原型链的方法##

function Parent(name,age){

this.name = name;

this.age = age;

this.sayName = function(){

console.log(this.name);

}

}

Parent.prototype.sayAge = function (){

console.log(this.age);

}

function Child (name,age,sex){

this.constructor(name,age);

this.sex = sex;

}

child.prototype = new Parent();

var c = new Child("zhangsan",30);

c.sayName;

c.sayAge;

这是重点,应该准确掌握理解:

##3.混合模式##

function Parent(name,age){

this.name = name;

this.age = age;

this.sayName = function(){

console.log(this.name);

}

}

有些不同;但是并未写完;

##闭包##

其实闭包我们平时使用很多;只是并未提及,下面就是一个例子:

function fn(){

var max =10;

return function bar(x){

if (x > max){

console.log(x);

}

}

}

var f1 = fn();

f1(15)//15

函数里面有函数,我们发现在函数执行完成之后x未被销毁;

还有匿名函数的方式:

<body>

<ul id="ul">

<li>1</li>

<li>2</li>

<li>3</li>

<li>4</li>

<ul>

<li>1</li>

<li>2</li>

<li>3</li>

<li>4</li>

</body>

<script>

var lis = document.getElementById("ul").getElementsByTagName("li");

for(var i = 0; i < lis.length; i++){

(function(i){

lis[i].onclick = function(){

console.log(i);

}

}(i));

}

注意这两个i不同,第一个为形参;第二个是我们定义的循环变量;

这里的i没有被销毁;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: