JS基本知识

来源:互联网 发布:dwcs6安装 mac 编辑:程序博客网 时间:2024/05/22 06:57
1.js的数据类型:数值,布尔,字符串,对象和数组
   对象类型:var currentDay=new Date()
   数组类型:var arr=new Array(4)
2.表达式和运算符
JS中的运算符分为算术,比较,逻辑,赋值等运算符。其中有一个”==“和”===“需要注意的是,前者会将类型进行转换来比较,后者只要类型不同就直接返回false
3.js函数
js函数定义如下:
function 函数名(参数列表)
{
函数体
retrurn 表达式
}
4.JavaScript面向对象的实现
面向对象中有几个概念:一切事物皆对象,对象具有封装性和继承特性,对象与对象之间使用消息通信,各自存在信息隐藏
JavaScript语言是通过一种叫做原型(prototype)的方式来实现面向对象编程的。
5.JavaScript内置对象
(1)String:String对象只有一个属性,即length,它是只读的。length属性只可用于返回字符串长度,不能在外部修改它
(2)Date:JavaScript Date对象提供了一种方式来处理日期和时间。您可以用许多不同的方式对其进行实例化,具体取决于想要的结果。
(3)Array:JavaScript对象是一个存储变量的变量,您可以用它一次在一个变量中存储多个值,它有许多方法允许您操作或收集有关它所存储的值的信息。尽管Array对象不差别对待值类型,但是在一个单一的数组中使用同类值是很好的做法。因此,在同一数组中使用数字和字符串不是好的做法。所有可用于Array对象的属性都是只读的,这意味着它们的值不能从外部予以更改。
6.面向对象深入分析
使用构造器创建对象。
//构造器Person本身是一个函数对象
function Person(){
//此处可以做一些初始化工作

}
//它有一个名叫prototype的属性
Person.prototype={
name:"张三",
age:26,
gender:"男",
eat:function(stuff){
debug("我在吃"+stuff)
}
}
//使用new关键字构造对象
var p=new Person()
debug(p.eat())
7.利用原型链Horse->Mammal->Animal实现继承
//声明Animal对象构造器
function Animal(){

}
//将Animal的prototype属性指向一个对象
//亦可直接理解为指定Animal对象的原型
Animal.prototype={
name:"animal",
weight:0,
eat:function(){
debug("Animal is eating")
}
}
//声明Mammal对象构造器
function Mammal(){
this.name="mammal"
}
//指定Mammal对象的原型为一个Animal对象
//实际上此处便是在创建Mamal对象和Animal对象之间的原型链
Mammal.prototype=new Animal()
//声明Horse对象构造器
function Horse(height,weight){
this.name="horse"
this.height=height
this.weight=weight
}
//将Horse对象的原型指定为一个Mamal对象,继续构建Horse与Mammal之间的原型链
Horse.prototype=new Mammal()
//重新指定eat方法,此方法将覆盖从Animal原型继承过来的eat方法
Horse.prototype.eat=function(){
debug("Horse is eating grass")
}
//验证并理解原型链
var horse=new Horse(100,300)
debug(horse.__proto__===Horse.prototype)
debug(Horse.prototype.__proto__===Mammal.prototype)
debug(Mammal.prototype.__proto__===Animal.prototype)
8.使用Simple Inheritance实现类继承
var Person=Class.extend({
_issleeping:true;
init:function(name){
this._name=name;
},
issleeping:function(){
return this._issleeping
}
});
//声明Programmar类,并继承Person
var Programmar=Person.extend({
init:function(name,issleeping){
//调用父类构造函数
this._super(name)
//设置自己的状态
this._issleeping=issleeping
}
});
var person=new Person("张三")
var diors=new Programmar("张江男",false)
//打印true
debug(person.issleeping())
//打印 false
debug(diors.issleeping())
//此处全为true,故打印true
debug(person instanceof Person && person instanceof Class && diors instanceof Programmar && diors instanceof Person &&diors instanceof Class)
9.JavaScript私有成员实现(使用闭包实现信息隐藏)
// User 
function User( pwd ) {
// 
var password = pwd;
// 
function getPassword() {
// password
return password;
}
// 
this.passwordService = function() {
return getPassword();
}
}
// 
User.prototype.checkPassword = function( pwd ) {
};
return this.passwordService() === pwd;
// 
var u = new User( "123456" );
// true
console.log( u.checkPassword( "123456" ) );
// undefined
console.log( u.password );
// true
console.log( typeof u.gePassword === "undefined" );
0 0
原创粉丝点击