JavaScript对象

1. 对象声明的两种方式
//最原始的方式:
var car = new Object();
car.make = "BMW";
car.model = "x6";
car.purchased =  new Date(2005, 3, 12);


// Json风格
var ride  = {
			make: 'bench',
			year: 2005,
			purchased: new Date(2010, 12, 30),
			owner: {
				name: 'caiwen'
			},
			someValues : [1, 2, 3]
		 };		
 };


2 js中函数就是对象
doSomething = function () {
     alert('let s do it');
};
alert(doSomething);


3 JS中 this是函数调用的上下文,就是调用函数的根对象, call 和 apply方法可以指定调用上下文
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Function Context Example</title>
    <script>
      var o1 = {handle:'o1'};
      var o2 = {handle:'o2'};
      var o3 = {handle:'o3'};
      window.handle = 'window';

      function whoAmI() {
        return this.handle;
      }

      o1.identifyMe = whoAmI;

      alert(whoAmI());
      alert(o1.identifyMe());
      alert(whoAmI.call(o2));
      alert(whoAmI.apply(o3));

    </script>
  </head>

  <body>
  </body>
</html>


输出

引用
windows
o1
o2
o3

你可能感兴趣的:(JavaScript)