var arr = ['你好','哈喽','早安']
var a = 1;//变量
arr.a = 1;//属性
//方法
arr.fn = function(){
alert(this) //this == arr
}
vDiv.onClick = function(){
alert(this) //this == vDiv
}
window.onload = function(){
atert(this) //this == window
}
//函数
function fn(){
alert(this) //this == window
}
函数fn等价于:
window.fn = function(){
alert(this) //this == window
}
也等价于:
fn = new Function("alert(this)")
构造函数:
var obj = new Object();
obj.name = '小明'
obj.showName = function(){
alert(name);
}
//构造函数
function creatPerson(name){
var this = new Object();
// this == obj
this.name = name
this.showName = function(){
alert(name);
}
return this;
}
var person1 = creatPerson(name);
等价于:
function creatPerson(name){
// this == creatPerson
this.name = name
this.showName = function(){
alert(name);
}
}
var person1 = new creatPerson(name);
prototype:原型
给类添加公共方法。不同的对象调用的是同一个方法。
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/,'') ;
}
str1.trim==str2.trim
var date = new Date();
typeof(Date) == function
对象内调用系统方法:
function Aee(id){
this.age = 12;
// this.fn = function(){
// alert(this.age)
// }
var _this = this;
setinterval(function(){ _this.fn()}.fn,1000);
document.getElementById(id).onclick = function(){
_this.fn();
}
}
Aee.prototype.fn = function(){
alert(this.age)
}
继承
Worker继承Person
function Worker(name,age,job){
Person.call(this,name,age);
// Worker.prototype = Person.prototype;//父类Person也多了一个showJob方法。
for(var i in Person.prototype){
Worker.prototype[i] = Person.prototype[i]//父类Person不会多一个showJob方法
}
this.job = job;
}
Worker.prototype.showJob(){
alert(this.job);
}