-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
javaScript进阶
工厂模式
function createPerson(name,age,sex) {
return{
name:name,
age:age,
sex:sex
}
}函数属性
- name
- length 需要接收多少个参数
- arguments 接收到的参数
- prototype 原型链
- constructor构造函数
arguments是个对象,类似数组,但是不是数组,因此不具有forEach等方法
this
执行环境
改变执行环境的函数方法
- bind(this)
- call(this,arg1,arg2....)
- apply(this, [arg1,arg2,...])
数据类型分类
- first class 可以作为参数,也可以作为返回值,或者赋值给变量
- second class 可以作为参数,不可返回,不可赋值给变量
- third class 不可以作为参数
闭包closure
闭包是指一个有权访问另一个函数作用域的函数
function CreatePerson(name) {
var selfName = name;
return{
getName: function() {
return selfName;
}
}
}构造函数
function Person(name,sex) {
this.name = name;
this.sex = sex;
this.getName = function() {
console.log(name);
}
}
var ps = new Person('gogo','girl');
var result = ps instanceof Person;
//结果为true缺陷: new方式会创建新的上下文环境,重复声明功能相同的函数(getName)
用原型解决上述问题
function Person(name,sex) {
this.name = name;
this.sex = sex;
}
Person.prototype.getName = function() {
console.log(this.name);
}属性的判断
- in 具有某个属性
- hasOwnProperty 自带的,非原型上的
继承
- 原型链继承
function Person(name,sex) {
}
function Student() {
}
//原型链继承
Student.prototype = new Person('jero','boy');缺陷
- constructor指向改变
- 共享的引用类型数据可能被污染
- 参数问题
- 借用构造函数进行继承
function Person(name,sex) {
this.name = name;
this.sex = sex;
}
Person.prototype.age = 18;
function Student(name,sex) {
//借用构造函数进行继承
Person.call(this,name,sex);
}
var stu = new Student('gogo','boy');
console.log(stu.age) //undefined 无法继承原型上面的属性或者方法 缺陷
- 无法继承原型上面的属性或者方法
- 组合继承
function Person(name,sex) {
this.name = name;
this.sex = sex;
}
Person.prototype.age = 18;
function Student(name,sex) {
//借用构造函数进行继承
Person.call(this,name,sex);
}
Student.prototype = new Person(); //原型链继承
Student.prototype.constructor = Student; //纠正构造函数
var stu = new Student('gogo','boy');
console.log(stu.age) //18 继承了原型上面的属性或者方法 小小的缺陷
- 多次调用了构造函数,导致父类实例存在无意义的属性,浪费内存
- 最佳实践
function Person(name,age) {
this.name = name;
this.age =age;
}
Person.prototype.drink = function() {
console.log('I want water');
}
function Client(name,age) {
Person.call(this,name,age);
}
//克隆一个父类的原型
var proto = Object.create(Person.prototype);
proto.constructor = Client;
Person.prototype = proto;
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels