javascript原型

1、在Javascript中只有五种简单类型,分别为null,undefined,boolean,String和Number.一种复杂类型:object。代码类型只有一种形式就是function

其实function也是一种变量 例如我们在写函数时:function Hello(){}等同于 var  Hello = function(){}这两者是相同的,只是写法不同。

Javascript并非完全的按顺序解释执行,而是在解释之前会对Javascript进行一次“预编译”,在预编译的过程中,会把定义式的函数优先执行,也会把所有var变量创建,默认值为undefined,以提高程序的执行效率

 1 <script type="text/javascript">
 2         function Hello() {
 3             alert("Hello");
 4         }
 5         Hello();
 6         function Hello() {
 7             alert("Hello World");
 8         }
 9         Hello();
10     script>
11 两次执行的效果都是 Hello World

2、作用域的问题
  变量用var定义 与不加var 的区别

 1 <html>
 2     <head>
 3         <script>
 4         
 5          b = "world";
 6          alert(a + " " + b);
 7          var a = "hello";
 8         </script>
 9     </head>
10 </html>

这样的运行结果是 undefined world 因为javascript在解释之前会进行一次“预编译”,在预编译的过程中,会把定义式的函数优先执行,也会把所有var变量创建,默认值为undefined

 1 <html>
 2     <head>
 3         <script>
 4         
 5          b = "world";
 6          alert(a + " " + b);
 7          a = "hello";
 8         </script>
 9     </head>
10 </html>

这样的运行结果会报错 a is not defined 

3、原型的使用

1  var Person = function(name,age){
2       this.name = name;
3       this.age = age;
4   };
5   
6   Person.prototype = {
7         show:function(){ alert(this.name+" "+this.age);}
8   };

这样所有Person对象使用的都会是同一个show函数 这个使用的json格式

也可以写成Person.prototype.show = function(){};这样写不如json格式简洁 ^-^

原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4096680.html