问题1: OOP 指什么?有哪些特性
- OOP是Object-orientend programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods. A feature of objects is that an object's procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of "this" or "self"). In OOP, computer programs are designed by making them out of objects that interact with one another. There is significant diversity of OOP languages, but the most popular ones are class-based, meaning that objects are instances of classes, which typically also determine their type. -- 来自 wiki
- OOP的特性:
1.继承性:可以解决代码复用,让编程更加靠近人类思维。当多个类存在相同的属性(变量)和方法时,可以从这些类中抽象出父类,在父类中定义这些相同的属性和方法,所有的子类不需要重新定义这些属性和方法,只需要通过继承父类中的属性和方法。
2.封装性:封装就是把抽象出来的数据和对数据的操作封装在一起,数据被保护在内部,程序的其它部分只有通过被授权的操作(成员方法),才能对数据进行操作。
3.多态性:指一个引用(类型)在不同情况下的多种状态。也可以理解成:多态是指通过指向父类的引用,来调用在不同子类中实现的方法。多态利于代码的维护和扩展,当我们需要使用同一类树上的对象时,只需要传入不同的参数就行了,而不需要再new 一个对象。
问题2: 如何通过构造函数的方式创建一个拥有属性和方法的对象?
function People(name,age) {
this.name = name
this.age = age
}
People.prototype.work = function() {
console.log('我的名字是:' + this.name + '我今年' + this.age + '岁了')
}
var people01 = new People('Jack',18)
people01.work()
问题3: prototype 是什么?有什么特性
- JavaScript 的每个对象都继承另一个对象,后者称为“原型”(prototype)对象。只有null除外,它没有自己的原型对象。每一个构造函数都有一个prototype属性,这个属性就是实例对象的原型对象。
问题4:画出如下代码的原型图
function People (name){
this.name = name;
this.sayName = function(){
console.log('my name is:' + this.name);
}
}
People.prototype.walk = function(){
console.log(this.name + ' is walking');
}
var p1 = new People('饥人谷');
var p2 = new People('前端');
问题5. 创建一个 Car 对象,拥有属性name、color、status;拥有方法run,stop,getStatus
function Car(name,color,status) {
this.name = name
this.color = color
this.status = status
}
Car.prototype = {
run: function() {
console.log('run')
},
stop: function() {
console.log('stop')
},
getStatus: function() {
console.log(this.status)
}
}
问题6.创建一个 GoTop 对象,当 new 一个 GotTop 对象则会在页面上创建一个回到顶部的元素,点击页面滚动到顶部。拥有以下属性和方法
1. `ct`属性,GoTop 对应的 DOM 元素的容器
2. `target`属性, GoTop 对应的 DOM 元素
3. `bindEvent` 方法, 用于绑定事件
4 `createNode` 方法, 用于在容器内创建节点