C#和JavaScript的区别

Strong and Loose Typing:

  • 强弱比较
// C#
var customer = new Customer(); //var is compiler inferred

//Javascript
var customer = new Customer(); //var is variable declaration

C#:var变量由编译器决定合适的类型,此例为Customer类型

JavaScript:var代表变量的意思,没有类型的强制

  • Compiler匹配最接近Type
//C#

var x = 0; // compiler暗示 to be int
bool isInt = x is int;  //x是int类型,右边是true
x = new object();  //C#定义过的变量需要保持typ
//Javascript

var x = 0; //creates variable x that holds a number
bool isNumber = typeof x == "number";  //works but limited
x = new object();  // no problem, can redefie the x with new type
  • OO里的Strong typing:
//C#
class Dog : Animal, IMoveable {...}
class Car : Vehicle, IMoveable {...}

//Accept any animal (base class has Feed Methord)
void Feed(Animal ani) {ani.Feed();}


//Accept any object that implements interface
void Move(IMoveable object) {object.Move();}

Dog可以放入Feed方法,因为继承自animal

Dog和Car都可以放入Move方法,因为interface

//JavaScript

//Accept any object
//(must implement Feed function)
functionFeed(ani) {ani.Feed();}


//Accept any object 
//must implement move methord
function Move(object) {object.Move();}

 

不论是何种type的object只要其有Feed方法

Dynamic Typing:

即使定义过x对象,也可以随时增加其属性和方法。

Language Basics:

  • 整体程序调用流程:

C#需要有一个入口程序,然后一步步的调用下去

Javascript是按照一行行执行下去,像Commond命令行

Language Closures:

在一个scope里x就一直可以用

Language Coalesce:

 

 

 

Javascript的基本元类型: 

  1. Special Type:null & undefined
    //javascript
    
    var a = null;  //"null"
    var b = c;  //"undefined"
  2. Value Type:
//JavaScript

var a = typeof 1;                //number
var b = typeof 1.0;              //number
var c = typeof true;            //true
var d = typeof false;            //false
var e = typeof "hello world"    //string

注意:type detector, 就象用as,is关键字在C#里

//javascript

var x = 1;
var typeName = typeof x;  //"number"
  1.  Number Type:

 

special value

 

  1.  Bollean Type:

 一般用来控制程序流程的

JavaScript有很好的Coalescing机制,比如测试一个function传入的参数是否为空("")还是有字符(“hello”),从而控制程序流程

 

  1.   String Type:

 

 

注意:string.length return的是长度的bytes而不是实际characters的个数

 

Javascript的reference type:

  1. object type:

 

  1. Array type(后一个是array object JSON serilazation经常见)

Array的方法

 

Function type:

JavaScript也有function type,可以直接复制给一个变量或者类的属性值(当我们定义了对象有一个function type属性之后,可以直接使用object.function的形式)

 

 

 

posted @ 2013-10-14 16:23  若愚Shawn  阅读(711)  评论(0编辑  收藏  举报