1.js是完全的面向对象语言,其中类的创建格式如下:
var person = {
name:"zhanghow",
sex:"boy",
eat:function(food){
console.log("I'm eatting ",food)
}
} // 注意的是字段的赋值是冒号取代= 与Lua表的区别
字段的访问:1. person.name
2. person[“name"]
字段的添加直接类名.新加的字段名 = 内容 (或者是 “” 方法)
字段的删除:delete + 字段的访问 代码:
person.eat("apple")
console.log(person.sex)
delete person.sex // 删除字段
person.height = 182
console.log(person)
// 形式二
function HelloWorld(){
this.name = "李四",
this.print = function(){
return "js"
}
}
var hw = new HelloWorld()
console.log(hw.print())// js
console.log(hw.name) // 李四
2.两个变量的连接 + 或者 , (Lua中是 .. )
console.log("ABC","abc")// ABC abc
console.log("ABC"+"abc")// ABC abc
console.log(5,6) // 5 6
console.log(5 + 6) // 11
3.this使用规则:
// this的使用规则:1.在最外层外,this引用的是全局变量
// 2.函数内部根据调用方式的不同选择不同的对象
一般this出现在函数里时,只有在函数执行时才能确定this是什么,因为this是指那个调用这个函数的对象。
x = 5; // 全局变量
var obj = {
x:3,
doit:function(){
console.log("method is called" + this.x)
}
}
obj.doit()// 3 谁调用指向谁
var func = obj.doit;
func() // 5 因为this指的是调用这个函数的对象,这里引用了全局变量
//apply与call使用方式()
function f(){
console.log(this.x);
}
var obj={x:4}
f.apply(obj) // 4 通过apply调用f内部,this引用了对象obj
f.call({x:5}) // 5
console.log("ssssssssssss")
var obj={
x:3,
doit:function(){
console.log("method is called "+this.x)}
}
var obj2={x:4};
obj.doit() // 3
obj.doit.apply(obj2)// 4
function f(a,b)
{
console.log("this.x="+this.x+"a="+a+"b="+b);
}
f.apply({x:4},[1,2]) //作为第二个参数的数列中的元素都是函数f的参数
f.call({x:4},1,2) //从第二个参数起的参数都是函数f的参数
4.在类中的函数应避免This的歧义
在函数内若要引用“
全局
”This 就要在函数体内定义一个变量self来接收 This ,此后才可避免二义性。