var fun = new Function("name", "age", "alert('你的名字是 ' + name + ' 你的年龄是' + age)");
//调用函数
fun("zxc",15);
//弹出整个函数的定义,是一个匿名的函数
//alert(fun.toString());
//求函数的参数个数
//alert("该函数的参数为" + fun.length + "个");
//利用内部函数访问私有变量,返回的一个函数的引用,注意不要加()
//简单闭包的使用,闭包是不会释放内存的,慎用!
function test() {
var a = "zxc";
function inner(){
alert(a);
}
return inner;
}
//然后执行该函数
var result = test();
result();
//创建对象之一 :json对象
var json = {
"name":"i am zxc",
getName:function(){
return "heihei!";
}
}
alert(json.name);
alert(json.getName());
function Dog(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
alert(name);
};
this.getAge = function() {
alert(age);
};
};
var dog = new Dog("我是周星驰","不过我22岁啊");
dog.getName();
dog.getAge();
function Cat() {
this.catName = "对象属性定义一";
Cat.prototype.catName2 = "对象属性定义之二";
var catAge = "私有属性";
var prifun = function() {
alert("私有方法");
}
this.pufun = function() {
alert("公有方法1");
}
Cat.prototype.pufun2 = function() {
alert("公有方法2");
}
}
Cat.cc = "类属性,类似于Java的静态数据";
Cat.zz = function() {
alert("类方法");
}
alert(Cat.cc);
var cat = new Cat();
alert(cat.catName + cat.catName2);
Cat.zz();
cat.pufun();
cat.pufun2();
//实现继承
//父类
function Animal(name, age) {
this.name = name;
this.age = age;
this.getName = function() {
alert(name);
};
this.getAge = function(){
alert(age);
};
this.parent = function() {
alert("父类方法啊");
};
}
//继承方式一,本质上还是Dog,适用于有参
function Dog(name, age) {
//本身和参数列表
Animal.apply(this, [name, age]);
this.mymethod = function() {
alert("我是狗啊");
};
}
//继承方式二,本质上变为Animal,适用于无参
function Cat(name, age) {
this.mymethod = function() {
alert("我是猫啊");
};
}
Cat.prototype = new Animal();
Cat.prototype.name = "zxc";
Cat.prototype.age = 18;
var dog = new Dog("狗啊","12");
dog.getName();
dog.getAge();
dog.mymethod();
var cat = new Cat("猫啊","14");
cat.parent();
//实现多态
function Animal() {
this.method = function() {
alert("动物方法哦");
}
}
function Dog() {
this.method = function() {
alert("狗方法哦");
}
}
function Cat() {
this.method = function() {
alert("猫方法哦");
}
}
//继承
Cat.prototype = new Animal();
Dog.prototype = new Animal();
function test(animal) {
if(animal instanceof Animal) {
animal.method();
}
}
test(new Animal());
test(new Dog());
test(new Cat());