日期:2014-05-16  浏览次数:20367 次

JavaScript学习(四)

1.this关键字

??在方法内部,this关键字就变成了调用该方法的对象;

??o.m();在m内部,this就是指向 o

?

??在<script>内部写的函数中,使用this,this指向全局对象(因为从本质意义上讲,是全局对象的一个方法而已)

?

?

2.原型对象(继承的根基)

?

每个对象都继承原型对象的所有属性。

?

对象属性的读取:先读对象本身的属性,如果没有再读其原型的属性,如果在原型中也没有找到,即未定义

对象属性的赋值:只会设置对象本身的属性,不会去设置原型的属性。

?

使用原型,可以为对象动态的添加属性

?

3.模仿Java的类机制

?

// We begin with the constructor
function Circle(radius) {
    // r is an instance property, defined and initialized in the constructor.
    this.r = radius;
}

// Circle.PI is a class propertyit is a property of the constructor function.
Circle.PI = 3.14159;

// Here is an instance method that computes a circle's area.
Circle.prototype.area = function( ) { return Circle.PI * this.r * this.r; }

// This class method takes two Circle objects and returns the
// one that has the larger radius.
Circle.max = function(a,b) {
    if (a.r > b.r) return a;
    else return b;
}

// Here is some code that uses each of these fields:
var c = new Circle(1.0);      // Create an instance of the Circle class
c.r = 2.2;                    // Set the r instance property
var a = c.area( );             // Invoke the area( ) instance method
var x = Math.exp(Circle.PI);  // Use the PI class property in our own computation
var d = new Circle(1.2);      // Create another Circle instance
var bigger = Circle.max(c,d); // Use the max( ) class method
?

?

4.对象的属性和方法

?

constructor属性:引用的是构造函数,这个属性是由原型对象中继承而来的。

但是并不能保证constructor属性总是存在,因为此原型对象的属性引用可以替换;JavaScript1.1中是只读的,后来改成可写的了,不知道什么原因。

?

if ((typeof o == "object") && (o.constructor == Date))
    // Then do something with the Date object...
?

?

也可用instanceof来实现上面的功能:

?

if ((typeof o == "object") && (o instanceof Date))
    // Then do something with the Date object...
?

?

?