JavaScript adds properties and methods to objects
JavaScript can define properties and methods when defining a class, or dynamically add properties and methods after creating an object.
Dynamic addition of properties and methods is difficult to achieve in other object-oriented programming languages (C++, JavaScript, etc.), which is a reflection of the flexibility of JavaScript.
Create an object based on the Person class and add properties and methods to it: // Define class
<script>// 定义类
function Person(name,sex) {
this.name=name; // 定义一个属性 name
this.sex=sex; // 定义一个属性 sex
this.say=function(){ // 定义一个方法 say()
return "嗨!大家好,我的名字是 " + this.name + " ,性别是 " + this.sex + " 。";
}
}
// 创建对象
var zhangsan=new Person("张三","男");
zhangsan.say();
// 动态添加属性和方法
zhangsan.tel="029-81892332";
zhangsan.run=function(){
return " 我跑得很快! ";
}
// 弹出警告框
alert("姓名:"+zhangsan.name);
alert("姓别:"+zhangsan.sex);
alert(zhangsan.say());
alert("电话:"+zhangsan.tel);
alert(zhangsan.run());</script>
new file
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script>// 定义类
function Person(name,sex) {
this.name=name; // 定义一个属性 name
this.sex=sex; // 定义一个属性 sex
this.say=function(){ // 定义一个方法 say()
return "嗨!大家好,我的名字是 " + this.name + " ,性别是 " + this.sex + " 。";
}
}
// 创建对象
var zhangsan=new Person("张三","男");
zhangsan.say();
// 动态添加属性和方法
zhangsan.tel="029-81892332";
zhangsan.run=function(){
return " 我跑得很快! ";
}
// 弹出警告框
alert("姓名:"+zhangsan.name);
alert("姓别:"+zhangsan.sex);
alert(zhangsan.say());
alert("电话:"+zhangsan.tel);
alert(zhangsan.run());</script>
</head>
<body>
</body>
</html>
Preview
Clear
- Course Recommendations
- Courseware download
The courseware is not available for download at the moment. The staff is currently organizing it. Please pay more attention to this course in the future~
Students who have watched this course are also learning
Let's briefly talk about starting a business in PHP
Quick introduction to web front-end development
Large-scale practical Tianlongbabu development of Mini version MVC framework imitating the encyclopedia website of embarrassing things
Getting Started with PHP Practical Development: PHP Quick Creation [Small Business Forum]
Login verification and classic message board
Computer network knowledge collection
Quick Start Node.JS Full Version
The front-end course that understands you best: HTML5/CSS3/ES6/NPM/Vue/...[Original]
Write your own PHP MVC framework (40 chapters in depth/big details/must read for newbies to advance)
















