批改状态:合格
老师批语:
<script>let a = 1;console.log(a);//1</script>
let a = 1;//console.log(a);function foo() {let a = 5;return a;}console.log(foo());//5
{let m = 8;const M = 9;}console.log(M);console.log(m);//均会报错
function foo() {let a = 0;return function f(params) {return a;}}let f = foo();console.log(f());
const arr = ["cat", "dog", "pig"];let i = 0;while (i < arr.length) {console.log(`animal: ${arr[i]}`);i += 1;}//animal: cat//animal: dog//animal: pig
let i = 1;do {i += 1;console.log(`animal: ${arr[i]}`);} while (i < arr.length - 1);//animal: pig
const stu = {id: 1,name: "Jack",gender: "male",graduate: false}for (const key in stu) {console.log("%c%s", "color:green", stu[key]);}//1//Jack//male//false
for (const item of arr) {console.log(item);}//animal: cat//animal: dog//animal: pig
JavaScript 常被描述为一种基于原型的语言 (prototype-based language)——每个对象拥有一个原型对象,对象以其原型为模板、从原型继承方法和属性。原型对象也可能拥有原型,并从中继承方法和属性,一层一层、以此类推。这种关系常被称为原型链 (prototype chain),它解释了为何一个对象会拥有定义在其他对象中的属性和方法。
准确地说,这些属性和方法定义在Object的构造器函数(constructor functions)之上的prototype属性上,而非对象实例本身。
function User(name, age) {this.name = name;this.age = age;this.info = function () {return { name: this.name, age: this.age };}}
function User(params) {this.p = params;}const user = new User("hehe");console.log(user);//user对象的原型console.log(user.__proto__);//user构造函数的原型console.log(User.prototype);console.log(user.__proto__ === User.prototype);
原型链
常见定义做法:
function User(name, age) {this.name = name;this.age = age;// this.info = function () {// return { name: this.name, age: this.age };// }}//将info()放到原型prototype属性中User.prototype.info = function () {return { name: this.name, age: this.age };};//生成对象const user = new User("Tom", 23);console.log(user);//User {name: "Tom", age: 23}console.log(user.info());//{name: "Tom", age: 23}
class Animal {//构造方法constructor(name, leg) {this.name = name;this.leg = leg;}//原型方法info() {return { name: this.name, leg: this.leg, isPet: this.#isPet };}//静态方法static eat() {return "food";}//静态属性static nature = "creature";//私有属性#isPet = false;//访问器方法 getter, setterget isPet() {return this.#isPet;}set isPet(value) {this.#isPet = value;}}const cat = new Animal("Cat", 4);const bird = new Animal("Bird", 2);console.log(cat.info());//{name: "Cat", leg: 4, isPet: false}console.log(bird.info());//{name: "Bird", leg: 2, isPet: false}console.log(`动物吃:${Animal.eat()}`);//动物吃:foodconsole.log(`动物本身是:${Animal.nature}`);//动物本身是:creatureconsole.log(`猫是宠物吗? ${cat.isPet}`);//猫是宠物吗? falsecat.isPet = true;console.log(`猫是宠物吗? ${cat.isPet}`);//猫是宠物吗? true//继承class Dog extends Animal {//继承//第一步必须执行父类构造方法,否则无法使用thisconstructor(name, type) {super(name, 4);//新成员初始化this.type = type;}info() {return { name: this.name, leg: this.leg, type: this.type };}//父类的私有属性不会被继承}const dog = new Dog("Dog", "哈士奇");console.log(dog.info());//{name: "Dog", leg: 4, type: "哈士奇"}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号