javascript是一个单线程的语言,但是可以通过代码调度在特定的时间运行。
对于js而言,每个实例化的对象都有以下的方法和属性(也就是说共有的,既然共有那麽就是在原型上的了):
(1):constructor,constructor被用来创建对象,比如 var o = new Object();那么constructor 就是 Object()函数。
(2):hasOwnProperty(propertyname),这表明如果一个实例化的对象(不是原型)存在给定的属性;注意的是属性名必须是字符串的形式。
(3):isPrototypeOf(object),判定一个对象是否是另一个对象的原型。
alert(Person.prototype.isPrototypeOf(person1)); //true
alert(Person.prototype.isPrototypeOf(person2)); //true
(4):propertyIsEnumerable(propertyname), 一个给定的属性可以用for-in语句枚举;同hasOwnProperty()一样,属性名必须是字符串。
(5):toString():返回对象的字符串形式
(6):valueOf():返回一个等于对象的字符串,布尔,字符串的值;这个经常返回和toString()一样的值。
对于js函数内部变量而言,函数执行结束,内部变量也就被销毁了。
对于判定变量的类型,基值类型变量用typeof ,引用类型变量用instance of最好了。
对于ECMAScript而言,函数(首字母大写)就是构造函数,(一般首字母大写,函数返回类型:Object.prototype.toString.call(a)返回[object Function])。参考一个例子:
function Person(name, age, job){
this.name = name;
this.age = age;
this.job = job;
this.sayName = new function(){ return this.name }; //logical equivalent
}
var person1 = new Person('Nicholas', 29, 'Software Engineer');
var person2 = new Person('Greg', 27, 'Doctor');
alert(person1.sayName)
alert(person1.sayName == person2.sayName); //false 不是原型上的,是对象的实例化
2:(function(){alert('ddd')})(); //ddd
3:var x=new function(){ return new String('ddd')};
alert(x); //ddd
4:var yx01 = new function() {return "ddd"};
alert(yx01);
将返回显示[object object] ,此时该代码等价于:
function 匿名类(){
return "ddd";
}
var yx01 = new 匿名类();
alert(yx01);
提示:注意 new function 和 new Function的区别。
看一个继承的例子:
function A(){
this.name='ikol';
this.hello='hello world';
}
A.prototype.getName=function(){
return this.name;
};
A.prototype.sayHello=function(){
return this.hello;
}
function B(){
A.call(this);
};
B.prototype=A.prototype;
var b=new B();
console.log(b.getName());
console.log(b.sayHello());
下面的看一个原型的例子:
function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
//继承自SuperType
SubType.prototype = new SuperType();
//试着增加一些新的方法 - 这将清空(覆盖)上面的一行
SubType.prototype = {
getSubValue : function (){
return this.subproperty;
},
someOtherMethod : function (){
return false;
}
};
var instance = new SubType();
alert(instance.getSuperValue()); //错误!
再看一个原型的例子代码如下,图形描述附最后:
function SuperType(name){
this.name = name;
this.colors = [“red”, “blue”, “green”];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
//inherit properties
SuperType.call(this, name);
this.age = age;
}
//inherit methods
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function(){
alert(this.age);
};
var instance1 = new SubType(“Nicholas”, 29);
instance1.colors.push(“black”);
alert(instance1.colors); //”red,blue,green,black”
instance1.sayName(); //”Nicholas”;
instance1.sayAge(); //29
var instance2 = new SubType(“Greg”, 27);
alert(instance2.colors); //”red,blue,green”
instance2.sayName(); //”Greg”;
instance2.sayAge(); //27