javascript学习笔记

1、搜索栏URI编解码

1.1.1.$(selArr[i])有时报错,浏览器奔溃

1.1.2 四个为false的值

 

Value

Context in which value is used

 

String

Number

Boolean

Object

Undefined value

"undefined"

NaN

false

Error

null

"null"

0

false

Error

Nonempty string

As is

Numeric value of string or NaN

TRue

String object

Empty string

As is

0

false

String object

0

"0"

As is

false

Number object

NaN

"NaN"

As is

false

Number object

Infinity

"Infinity"

As is

true

Number object

Negative infinity

"-Infinity"

As is

TRue

Number object

Any other number

String value of number

As is

true

Number object

true

"true"

1

As is

Boolean object

false

"false"

0

As is

Boolean object

Object

toString( )

valueOf( ), toString( ), or NaN

true

As is

 

 

正确写法 : for(var i = 0;i < selArr.size();i ++){

错误写法 : for(var i  in selArr ),

这种写法在一般是没有问题的,但是在jquery,这确实是一个bug.

一、定义和用法

encodeURI() 函数可把字符串作为 URI 进行编码。

语法

encodeURI(URIstring)

参数

描述

URIstring

必需。一个字符串,含有 URI 或其他要编码的文本。

返回值

URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。

说明

该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ' ( ) 

该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?:@&=+$,#

提示和注释

提示:如果 URI 组件中含有分隔符,比如 和 #,则应当使用 encodeURIComponent() 方法分别对各组件进行编码。

此方法的解码为decodeURI()

 

Javascript 可以操纵html所有的标签跟属性,自然也可以操作span标签;

1.1.3url  % 转义

1.1.3.1 . % 浏览器 url 有特殊的含义 使用时 一定要对 专业成 %25 才能够被后台使用,否则将会收不到参数的结果 。

1.1.3.2 . "&"要转码为"%26"

http://www.blogjava.net/xiaomage234/archive/2007/12/21/169473.html

 

2javascript中函数 和函数对象的区别?

函数(方法Function)是对js操作过程的封装。。以后操作同样的过程。。只要调用相应的函数(方法)即可。。
对象同样是对js代码封装。。不过对象可以封装函数(方法)。。。比如把某一类的函数(方法)都封装到某个对象中。。这样可以系统的管理调用函数(方法)。。。
比如我写了很多的函数。。我只要知道我想要调用的函数是哪一类的。。。声明相应的对象。。就可以很容易的找到我要调用的函数(方法)。

2.1、关于函数对象

2.1.1函数是进行模块化程序设计的基础,编写复杂的Ajax应用程序,必须对函数有更深入的了解,javascript中的函数不同于其他的语言,每个函数都是作为一个对象被维护和运行的。通过函数对象的性质,可以很方便的将一个函数赋值给一个变量或者将函数作为参数传递

执行时,函数都是被维护为一个对象;

2.1.2函数对象对应的类型是Function,正如数组对象对应的类型是Array,日期对象对应的类型是Date一样,可以通过new Function()来创建一个函数对象,也可以通过function关键字来创建一个对象。

2.1.3函数对象与其他用户所定义的对象有着本质的区别,这一类对象被称之为内部对象

正如数组对象对应的类型是Array等内置对象,javascript有内部的实现机制,例如:

function myFunction(a,b){  
  return a+b;  
}  
//等价于  
var myFunction=new Function("a","b","return a+b");   

the new operator creates a new object and then invokes the constructor function, passing the newly created object as the value of the this keyword.

3function: 

A function is a piece of executable code that is defined by a JavaScript program or predefined by the JavaScript implementation.

3.1、方法的参数

1js中有内部对象arguments,可以把他当成数组访问参数,

即使在定义方法的时候没有设置参数,但在使用方法是加入参数

也可以使用这个对象访问到加入的参数

例如:function invoke(){

If(arguments[0] != null){alert(‘我是参数1’);}

}

 

此时,虽然参数没有定义属性,但是我可以这么调用invoke(‘abc’);

 

1、 js方法中若有定义参数,在调用方法时也不必设置全部参数

例如:function invoke(arg1,arg2,arg3){

If(arg1) return null;

If(arg2)  return null;

If(arg3) return null;

}

调用这个方法的时候不需要设置全部参数,js是一种非常宽松的语言,

你可以这么调用:invoke(‘参数1);

也可以   :invoke(‘参数1’,‘参数2’);

你甚至可以   :invoke(‘参数1’,‘参数2’,‘参数3’,‘参数4);

4Object

4.1An object is a collection of named values.

These named values are usually referred to as properties of the object.

And, Properties of objects are, in many ways, just like JavaScript variables; they can contain any type of data, including arrays, functions, and other objects.

4.2constructor property

In JavaScript, every object has a constructor property that refers to the constructor function that initializes the object.

5method: 

when a function value is stored in a property of an object, that function is often called a method,

and the property name becomes the method name.

6Object as associative Array;

Objects in JavaScript can serve as associative arrays;

image["width"] and image["height"] just the same as aOjbect.width and oabject.height;

7create object

7.1、objects are created by invoking special constructor functions.

var o = new Object( );

var now = new Date( );

var pattern = new RegExp("\sjava\s", "i");

 

Once you have created an object of your own, you can use and set its properties whatever you desire:

var point = new Object( );

point.x = 2.3;

point.y = -1.2;

7.2you can also create an object by Object Literals.

An object literal is a comma-separated list of property name/value pairs, enclosed within curly braces.

Each property name can be a JavaScript identifier or a string, and each property value can be a constant or any JavaScript expression.

var point = { x:2.3,y:-1.2 };

7.3Object literals can also be nested. For example:

var rectangle = { upperLeft: { x: 2, y: 2 },

                  lowerRight: { x: 4, y: 4}

};

7.4 Deleting Object: 

delete Object;

8Object Conversion

8.1、When the object is used in string context,the object will use toString() method of itself and use the uses the string value returned by this method;

8.2numeric 

When the object is used in numeric context, the object will invoke toString() method first,and then attempt to convert this string context to numeric context .

9literal:

A literal is a data value that appears directly in a program;

 

10identifier

An identifier is simply a name. In JavaScript, identifiers are used to name variables and functions, and to provide labels for certain loops in JavaScript code;

11Object as a associative arrays:

We can access the value of property of a specified object using array notation with string expression:

Object[“property1”]; or Object[property2];  //caution:property must be a identifer

Note that property2 is a string context instead of an identifier;

12function is a datatype;

In many languages, including Java, functions are only a syntactic feature of the language: they can be defined and invoked, but they are not datatypes. 

The fact that functions are true values in JavaScript gives a lot of flexibility to the language. It means that functions can be stored in variables, arrays, and objects, and it means that functions can be passed as arguments to other functions.

12.1function literial

a function literal looks just like a function definition, except that it does not have to have a name. The big difference is that function literals can appear within other JavaScript expressions.

12.2constructor function

A function designed to be used with the new operator is called a constructor function or simply a constructor.

have defined a class of objects simply by defining an appropriate constructor function

12.3function as data

function square(x) { return x*x; }

This definition creates a new function object and assigns it to the variable square. The name of a function is really immaterial; it is simply the name of a variable that refers to the function. The function can be assigned to another variable and still work the same way:

13prototype

13.1 .1The essence of prototype

1You can treat prototype as the core of a javascript class.

2Each class has one prototype object, with one set of properties

3But there are potentially many instances of a class, each of which inherits those prototype properties.

 

13.1.2Write and read prototype

1Read

When you read property p of an object o, JavaScript first checks to see if o has a property named p. If it does not, it next checks to see if the prototype object of o has a property named p. This is what makes prototype-based inheritance work.

2Write

property inheritance occurs only when you read property values, not when you write them.

If you set the property p in an object o that inherits that property from its prototype, what happens is that you create a new property p directly in o.

13.2others 

 If username is null, undefined, 0, "", or NaN, it converts to false

 

14、继承

141面向对象与基于对象

几乎每个开发人员都有面向对象语言(比如C++C#Java)的开发经验。 在传统面向对象的语言中,有两个非常重要的概念 类和实例。 类定义了一类事物公共的行为和方法;而实例则是类的一个具体实现。 我们还知道,面向对象编程有三个重要的概念 封装、继承和多态。

但是在JavaScript的世界中,所有的这一切特性似乎都不存在。 因为JavaScript本身不是面向对象的语言,而是基于对象的语言。 这里面就有一些有趣的特性,比如JavaScript中所有事物都是对象, 包括字符串、数组、日期、数字,甚至是函数,比如下面这个例子:

1

2

3

4

5

6

7

8

9

10

// 定义一个函数 - add

function add(a, b) {

    add.invokeTimes++;

    return a + b;

}

// 因为函数本身也是对象,这里为函数add定义一个属性,用来记录此函数被调用的次数

add.invokeTimes = 0;

add(1 + 1);

add(2 + 3);

console.log(add.invokeTimes); // 2

 

14.2模拟JavaScript中类和继承

在面向对象的语言中,我们使用类来创建一个自定义对象。然而JavaScript中所有事物都是对象,14.2.1、原型

这就需要引入另外一个概念 原型(prototype),我们可以简单的把prototype看做是一个模版,新创建的自定义对象都是这个模版(prototype)的一个拷贝 (实际上不是拷贝而是链接,只不过这种链接是不可见,给人们的感觉好像是拷贝)。

让我们看一下通过prototype创建自定义对象的一个例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// 构造函数

   function Person(name, sex) {

       this.name = name;

       this.sex = sex;

   }

   // 定义Person的原型,原型中的属性可以被自定义对象引用

   Person.prototype = {

       getName: function() {

           return this.name;

       },

       getSex: function() {

           return this.sex;

       }

   }

这里我们把函数Person称为构造函数,也就是创建自定义对象的函数。可以看出,JavaScript通过构造函数和原型的方式模拟实现了类的功能。 
创建自定义对象(实例化类)的代码:

?

1

2

3

4

var zhang = new Person("ZhangSan", "man");

console.log(zhang.getName()); // "ZhangSan"

var chun = new Person("ChunHua", "woman");

console.log(chun.getName()); // "ChunHua"

当代码var zhang = new Person("ZhangSan", "man")执行时,其实内部做了如下几件事情:

创建一个空白对象(new Object())。

拷贝Person.prototype中的属性(键值对)到这个空对象中(我们前面提到,内部实现时不是拷贝而是一个隐藏的链接)。

将这个对象通过this关键字传递到构造函数中并执行构造函数。

将这个对象赋值给变量zhang

 

为了证明prototype模版并不是被拷贝到实例化的对象中,而是一种链接的方式,请看如下代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

function Person(name, sex) {

    this.name = name;

    this.sex = sex;

}

Person.prototype.age = 20;

var zhang = new Person("ZhangSan", "man");

console.log(zhang.age); // 20

// 覆盖prototype中的age属性

zhang.age = 19;

console.log(zhang.age); // 19

delete zhang.age;

// 在删除实例属性age后,此属性值又从prototype中获取

console.log(zhang.age); // 20

这种在JavaScript内部实现的隐藏的prototype链接,是JavaScript赖以生存的温润土壤, 也是模拟实现继承的基础

 

14.3如何在JavaScript中实现简单的继承? 
下面的例子将创建一个雇员类Employee,它从Person继承了原型prototype中的所有属性。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

function Employee(name, sex, employeeID) {

    this.name = name;

    this.sex = sex;

    this.employeeID = employeeID;

}

// 将Employee的原型指向Person的一个实例

// 因为Person的实例可以调用Person原型中的方法所以Employee的实例也可以调用Person原型中的所有属性。

Employee.prototype = new Person();

Employee.prototype.getEmployeeID = function() {

    return this.employeeID;

};

var zhang = new Employee("ZhangSan", "man", "1234");

console.log(zhang.getName()); // "ZhangSan

 

上面关于继承的实现很粗糙,并且存在很多问题:

在创建Employee构造函数和原型(以后简称类)时,就对Person进行了实例化,这是不合适的。

Employee的构造函数没法调用父类Person的构造函数,导致在Employee构造函数中对namesex属性的重复赋值。

Employee中的函数会覆盖Person中的同名函数,没有重载的机制(和上一条是一个类型的问题)。

创建JavaScript类的语法过于零散,不如C#/Java中的语法优雅。

实现中有constructor属性的指向错误,这个会在第二篇文章中讨论。

我们会在第三章完善这个例子。

 

JavaScript继承的实现

正因为JavaScript本身没有完整的类和继承的实现,并且我们也看到通过手工实现的方式存在很多问题, 因此对于这个富有挑战性的任务网上已经有很多实现了:

本资源来自:http://www.cnblogs.com/sanshi/archive/2009/07/08/1519036.html

15、总结functionObjectconstructorprototype

15.1new Function()的具体流程

15.1.1All functions have a prototype property that is automatically created and initialized when the function is defined.

15.1.2new

15.1.2.1new operator creates a new, empty object,(The initial value of the prototype property is an object with a single property. This property is named constructor and refers back to the constructor function with which the prototype is associated)

15.1.2.2and then sets the prototype of that object. Any properties you add to this prototype object will appear to be properties of objects initialized by the constructor.

15.1.3then invokes a constructor function as a method of that object.

 

中文解释:

函数只是一个操作过程

函数new 完之后,函数中所有的属性 就封装到新创建的对象中函数本

 

/*var obj = {

methodA:function(){

this.methodB();

},

methodB:function(){

alert('abc');

}

};*/

 

/*var company = new Company('name','desc');

company.produce('msg');*/

 

/*function Company(name,address) { 

this.number = 10;

    this.name = name; 

    this.address = address; 

    this.produce = function(message){ 

     window.alert(this.number);

     this.newPro(message); 

    } ;

    this.newPro = function(message){

     alert(message);

    };

} */

 

 

 

15.2this在各种环境中指代什么

15.2.1、在构造函数中,指代新创建的对象实例。

Function newConstructor(){

This.name = ‘apem’; //这里指代新创建的函数对象

}

15.2.2、当方法被调用时,this指代调用该方法的对象

Var objectA = {

methodA : { this.apem = ‘apem’; }

}

objectA.methodA(); //此时this指代objectA

15.2.3、如果一个函数被当作一个普通函数而不是对象方法来调用,那么此时函数中this指代的是window对象

Function justAFunction(){

This.alert(‘I am not a method,but just a reference of window object’);

}

 

If(variable != undefined){ justAFunction()}

16、解析 this.initialize.apply(this, arguments) 

一、 起因 
那天用到prototype.js于是打开看看,才看几行就满头雾水,原因是对js的面向对象不是很熟悉,于是百度+google了一把,最后终于算小有收获,写此纪念一下^_^。 
prototype.js代码片段

代码如下:
var Class = { 
    create: function() { 
        return function() { 
            this.initialize.apply(this , arguments); 
        } 
    } 

// Class使用方法如下
var A = Class.create(); 
A. prototype={ 
    initialize:function(v){ 
        this .value=v; 
    } 
    showValue:function(){ 
        alert(this.value); 
    } 

var a = new A(‘helloWord!'); 
a. showValue();//弹出对话框helloWord

l initialize是什么
l apply方法是干什么的? 
l arguments变量呢? 
为什么new A后就会执行initialize方法? 
寻找答案:

二、 Js的面向对象 
initialize是什么
只不过是个变量,代表一个方法,用途是类的构造函数。 
其具体功能靠js的面向对象支持,那么js的面向对象是什么样子的那?和java 的有什么相同与不同? 
看代码:

代码如下:
var ClassName = function(v){ 
    this.value=v; 
    this.getValue=function(){ 
        return this.value; 
    } 
    this.setValue=function(v){ 
        this.value=v; 
    } 
}

那么JS中的函数和类有什么不同呢? 
其实是一样的,ClassName就是一个函数,当出现在new后面的时候就作为一个构造函数来构造对象。 

代码如下:
var objectName1 = new ClassName(“a”);//得到一个对象

其中objectName1就是执行ClassName构造函数后得到的对象,而在ClassName函数中的this指的就是new之后构造出来的对象,所以objectName1会后一个属性和两个方法。可以通过这样来调用他们:

代码如下:
objectName1.setValue(''hello''); 
alert(objectName1.getValue());//对话框hello 
alert(objectName1.value) ;//对话框hello

那么

复制代码 代码如下:
var objectName2 = ClassName(“b”);//得到一个对象

这样objectName2得到的是什么呢?显然是方法的返回值,这里ClassName只作为了一个普通的函数(虽然首字母大写了)。但是在之前写的ClassName中并没有返回值,所以objectName2会是undifinded那么“b”赋给谁了呢?在这并没有产生一个对象,而只是单纯的执行这个方法,所以这个“b”赋值给了调用这个方法的对象window,证据如下: 
var objectName2 = ClassName(“b”);//得到一个对象 
alert(window.value)//对话框
所以JS中的所有function都是一样的,但是用途可能是不同的(用作构造对象抑或是执行一个过程)。 
下面该回到主题了initialize是干什么的?

代码如下:
var Class = { 
    create: function() { 
        return function() { 
            this.initialize.apply(this , arguments); 
        } 
    } 

var A = Class.create();

这段代码是构造个一个function复制给A,这个function

复制代码 代码如下:
function() { 
    this.initialize.apply(this , arguments); 
}

并且后面这个方法是用来做构造函数的。当使用这个构造函数来构造对象的时候,会让构造出来的这个对象的initialize变量执行apply()方法,apply()的用途后面在说,继续说initialize。这样在初始化对象的时候会联系到initialize(怎么联系就要看apply的了)。 
那么

代码如下:
A.prototype={ 
    initialize:function(v){ 
        this .value=v; 
    } 
    showValue:function(){ 
        alert(this.value); 
    } 
}

是什么意思呢? 
Prototype原型的意思。A是一个function(),那么A. prototype,就是function中的一个变量,其实是个对象。这个对象拥有什么方法,那么function产生的对象就拥有什么方法,故 
var a = new A(‘helloWord!'); 
a. showValue();//弹出对话框helloWord
所以a对象也会有initialize方法,不只如此,每一个有A构造出来的对象都会有一个initialize方法,而在前面说过,构造的时候会调用构造函数,构造函数里面会让initialize去调用apply方法,于是在new A(‘helloWord!')的时候initialize回去调用apply方法。这也就是调用了一个初始化的方法。

三、 call()apply() 
下面开始研究apply(),在网上找了几个资料,并结合自己的研究,了解了call()apply()的功能。功能基本一样,function().call(object,{},{}……)或者function().apply (object,[……])的功能就是对象object调用这里的funciton(),不同之处是call参数从第二个开始都是传递给funciton的,可以依次罗列用隔开。而apply只有两个参数,第二个是一个数组,其中存储了所有传递给function的参数。 
this.initialize.apply(this , arguments); 
是什么意思? 
这里的第一个this,是指用new调用构造函数之后生成的对象,也就是前面的a,那么第二个this也当然应该是指同一个对象。那这句话就是this(也就是a)调用initialize方法,参数是arguments对象(参数的数组对象),所以在构造函数执行的时候,对象a就会去执行initialize方法来初始化,这样就和单词“initialize”的意思对上了。 
那么执行initialize方法的参数怎么传递进去的呢?

四、 Arguments对象 
这段代码能说明一切了:

代码如下:
function test(){ 
    alert(typeof arguments); 
    for(var i=0; i<arguments.length; i++){ 
        alert(arguments[i]); 
    } 

test("1","2","3"); 
test("a","b");

执行后alert(typeof arguments);会显示object,说明arguments是对象。然后会依次打出123。说明arguments就是调用函数的实参数组。

代码如下:
var Class = { 
    create: function() { 
        return function() { 
            this.initialize.apply(this , arguments); 
        } 
    } 
}

arguments 就是create返回的构造函数的实参数组,那么在 
var a = new A(‘helloWord!'); 
的时候‘helloWord!'就是实参数组(虽然只有一个字符串),传递给方法apply,然后在调用initialize 的时候作为参数传递给初始化函数initialize

17String->JsonObject

package package_1;

import java.lang.StringBuffer;

import java.awt.Window.Type;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.BufferedReader;

import java.net.URL;

import net.sf.json.JSONObject;

import com.google.gson.Gson;

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;

import com.google.gson.JsonElement;

 

public class ChinaWeatherAPI {

public static void main(String[] args){

String jsonString = "{"field1":"value1","field2":"value2"}";

JsonParser parser = new JsonParser();

JsonObject jo = (JsonObject)parser.parse(jsonString);

JsonElement ele = jo.get("field1");

String value1 = ele.getAsString();

}

}

 

18JS object -> String

18.1String-> JS object

全局函数 var obj = eval(string)

18.2JS object –> String

for(var property in obj){

str += property+':'+obj[property]+',';

}

 

19.js属性的特性

19.1 undefined

如果输入或使用的变量是undefined,那么js不会报错,浏览器不会执行这个命令;

20、表单

20.1、纯文本数据表单提交

这中纯文本表单提交方式十分简单,他的发送形式是:

Name1=value1&name2=value2…

20.1.1、纯文本数据的获取方法

目的:是当然是为了异步发送数据

方法1jquery.serialize();//结果Name1=value1&name2=value2…

方法2: 每个js对象都有id name className style value等常用属性

Var str = “”;

For(var I = 0;I < form.elements.length;I ++){

Str+= ‘&’+form.elements[i].name+’=’+ form.elements[i].value;

}

20.2、含2进制数据表单提交

20.2.1、提交的详情

Boundary=-----------------------------7d72ee19d0998
Content-Disposition: form-data; name="c"

af
-----------------------------7d72ee19d0998
Content-Disposition: form-data; name="d"


-----------------------------7d72ee19d0998
Content-Disposition: form-data; name="e"

d1
-----------------------------7d72ee19d0998
Content-Disposition: form-data; name="e"

f3
-----------------------------7d72ee19d0998
Content-Disposition: form-data; name="f鐨�"; filename="g:/My Documents/My Pictures/32a022829b3c2473ada0faa4db48a308_034711.jpg"
Content-Type: image/pjpeg

//往下都2进制数据,(乱码省略)

���� JFIF   d d  �� Ducky     (  �� 

-----------------------------7d72ee19d0998—

20.2.2 异步文件上传

http://www.cnblogs.com/linzheng/archive/2010/10/31/1865671.html

使用方法:

function ajaxFileUpload()
    {
        $("#loading")
        .ajaxStart(function(){
            $(this).show();            
        })
        .ajaxComplete(function(){
            $(this).hide();            
        });

        $.ajaxFileUpload
        (
            {
                url:'Upload.ashx',
                secureuri:false,
                fileElementId:'fileToUpload',
                dataType: 'json',
                success: function (data, status)
                {                
                    if(typeof(data.error) != 'undefined')
                    {
                        if(data.error != '')
                        {
                            alert(data.error);
                        }else
                        {
                            alert(data.msg);
                        }
                    }
                },
                error: function (data, status, e)
                {
                    alert(e);
                }
            }
        )
        
        return false;

    }

21 jquery.extend(被复制对象,新对象)

若新对象中有属性名和被复制对象的属性名一致,那么最后生成的对象以 新对象为准

方法同理

var options = {

data: '123',

url : 123,

success: function(){}

};

 

var obj = $.extend(options,{

data : 'myData',

url : 'myUrl',

success : function(){

window.alert(this.data + this.url);

}

});

 

obj.success();

结果是 myDatamyUrl 

 

原文地址:https://www.cnblogs.com/apem/p/3480857.html