JS对象基础 闭包等
一.我们知道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没有被销毁;
最新文章
- 在离线环境中发布.NET Core至Windows Server 2008
- 最新JavaScript、Ajax典藏级学习资料下载分类汇总 (2011年12月21日更新)
- ZJOI day1总结
- ASP.NET 5中的ASP.NET Bundles跑到哪里去了?
- Web Application Project is configured to use IIS. Unable to access the IIS metabase.(配置为使用IIS Web应用程序xxxx项目。无法访问IIS元数据库。)
- ARM指令集----寻址方式
- NGUI学习笔记(五):缓动
- 教你使用Android SDK布局优化工具layoutopt
- 关于angular 自定义directive
- 装饰模式,制作一个蛋糕java
- Ubuntu 下配置Samba 实现Linux和windows之间文件共享
- 【NOIP2014】Day1题解+代码
- iOS 一招搞定去掉字符串开始的0,尤其是针对时间格式化
- 将一个实体转换成 Url 参数的形式 ?a=a&;b=b
- js解析base64
- 第一篇----mysql体系
- C++进阶--const变量
- JavaScript-jQuery报TypeError $(...) is null错误(jQuery失效)解决办法
- 02--CSS的继承性和层叠性
- 主存储器与CPU的连接