The plug-in
Prettier-code Formatter must be installed for VScode, Shift + Alt + F for formatting Code
Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.
Who comes first, importClass or require
runtime.loadDex("./yashu.dex");
importClass(android.graphics.Rect);
let yashu = require("./yashu");
Copy the code
interface
The interface is displayed first, and other operations are left behind to relieve users’ anxiety
Naming conventions
- Avoid single character names and make your variable names descriptive.
// bad
function q() {
/ /... stuff...
}
// good
function query() {
/ /.. stuff..
}
Copy the code
- Use hump naming when naming objects, functions, and instances
// bad
var OBJEcttsssss = {};
var this_is_my_object = {};
var this-is-my-object = {};
function c() {};
var u = new user({
name: 'Bob Parr'
});
// good
var thisIsMyObject = {};
function thisIsMyFunction() {};
var user = new User({
name: 'Bob Parr'
});
Copy the code
- Use camel case capitals when naming constructors or classes
// bad
function user(options) {
this.name = options.name;
}
var bad = new user({
name: 'nope'
});
// good
function User(options) {
this.name = options.name;
}
var good = new User({
name: 'yup'
});
Copy the code
- Private attributes are named preceded by an underscore
_
// bad
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
// good
this._firstName = 'Panda';
Copy the code
- When saved to
this
Is used when referring to_this
.
// bad
function() {
var self = this;
return function() {
console.log(self);
};
}
// bad
function() {
var that = this;
return function() {
console.log(that);
};
}
// good
function() {
var _this = this;
return function() {
console.log(_this);
};
}
Copy the code
File naming conventions
File names must be all lowercase and may include underscores (_) or dashes (-), But no additional punctuation. Follow the convention that your project uses. Filenames’ extension must be.js.
- github
What is the javascript filename naming convention?
- Other 1
Js file naming convention
- All lowercase letters
- No Spaces
- Connect words with dashes (-)
- Library files can be comma (.) Is used to reflect versions or dependencies
Demo
- vue.min.js
- vue-router.js
- jquery.form.js
- Jquery – 1.4.2. Min. Js
- The other two
1. Project naming
Use all lowercase lines to separate battlefields e.g. Come_money
2. Directory naming
Refer to the name of the project. If there is a plural structure, use the plural naming method e.g. moneys, assets, components…
Js, CSS, LESS, SASS, stylus file naming
Use small hump naming conventions such as comemoney. js, moneyCome. CSS, moneyCome. Stylus
4. Name VUE Components
All component names are in large hump format such as ComeMoney. Vue, MoneyCome. Vue
- The above conventions are for reference only, and ultimately respect personal habits. However, if you reference a framework or library in your project, it is best to use their naming conventions first. In addition, it is best to use a common naming convention in a project, so that you and other developers can easily identify.
object
- Use the shorthand for object methods. Properties cannot be abbreviated. Methods can be abbreviated
// bad
const item = {
value: 1.addValue: function (val) {
return item.value + val
}
}
// good
const item = {
value: 1,
addValue (val) {
return item.value + val
}
}
Copy the code
- Don’t use it directly
Object.prototype
For examplehasOwnProperty
.propertyIsEnumerable
和isPrototypeOf
methods
Cause: These methods may be overridden by the Object’s own property of the same name – such as {hasOwnProperty: false} or the Object may be a null Object (object.create (null)).
// bad
console.log(object.hasOwnProperty(key))
// good
console.log(Object.prototype.hasOwnProperty.call(object, key))
// best
const has = Object.prototype.hasOwnProperty // cache the lookup once, in module scope.
console.log(has.call(object, key))
Copy the code
An array of
- Use slice when you need to copy arrays
var len = items.length,
itemsCopy = [],
i;
// bad
for (i = 0; i < len; i++) {
itemsCopy[i] = items[i];
}
// good
itemsCopy = items.slice();
Copy the code
- Use slice to convert an array-like object into an array
function trigger() {
var args = Array.prototype.slice.call(arguments); . }Copy the code
Deconstruction assignment
- Use destruct assignment when you need to use multiple values of an array
const arr = [1.2.3.4]
// bad
const first = arr[0]
const second = arr[1]
// good
const [first, second] = arr
Copy the code
string
- If the string is too long, do not use string concatenation line feeds
\
Instead, use+
const str = 'Tooth Tutorial tutorial tooth Tutorial' +
'Tooth Tutorial tutorial tooth Tutorial' +
'Tooth Uncle Tutorial'
Copy the code
- Do not use unnecessary escape characters in strings
// bad
const foo = '\'this\' \i\s \"quoted\"'
// good
const foo = '\'this\' is "quoted"'
Copy the code
- Build strings programmatically using joins instead of string concatenation
var items,
messages,
length, i;
messages = [{
state: 'success'.message: 'This one worked.'}, {state: 'success'.message: 'This one worked as well.'}, {state: 'error'.message: 'This one did not work.'
}];
length = messages.length;
// bad
function inbox(messages) {
items = '<ul>';
for (i = 0; i < length; i++) {
items += '<li>' + messages[i].message + '</li>';
}
return items + '</ul>';
}
// good
function inbox(messages) {
items = [];
for (i = 0; i < length; i++) {
items[i] = messages[i].message;
}
return '<ul><li>' + items.join('</li><li>') + '</li></ul>';
}
Copy the code
function
- Functional expression
// An anonymous function expression
var anonymous = function() {
return true;
};
// Named function expression
var named = function named() {
return true;
};
// Call the function expression immediately
(function() {
console.log('Welcome to the Internet. Please follow me.'); }) ();Copy the code
- Wrap self-executing anonymous functions in parentheses
(function () {
console.log('Welcome to the Internet. Please follow me.')
}())
Copy the code
- Do not declare a function in a non-function block and assign that function to a variable.
Note: The ECMA-262 definition defines a block as a set of statements. The function declaration is not a statement. Read ecMA-262’s description of this issue.
// bad
if (currentUser) {
function test() {
console.log('Nope.'); }}// good
if (currentUser) {
var test = function test() {
console.log('Yup.');
};
}
Copy the code
- Never name the parameter as
arguments
This will pass through the function scopearguments
Object.
// bad
function nope(name, options, arguments) {
/ /... stuff...
}
// good
function yup(name, options, args) {
/ /... stuff...
}
Copy the code
Arrow function
- Use arrow function markers when you must use function expressions (passing anonymous functions)
// bad
[1.2.3].map(function (x) {
const y = x + 1
return x * y
})
// good
[1.2.3].map((x) = > {
const y = x + 1
return x * y
})
Copy the code
Object properties
- use
.
To access object properties
const joke = {
name: 'haha'.age: 28
}
// bad
const name = joke['name']
// good
const name = joke.name
Copy the code
- Used when the accessed property is a variable
[]
const luke = {
jedi: true.age: 28,}function getProp (prop) {
return luke[prop]
}
const isJedi = getProp('jedi')
Copy the code
Variable declarations
- Declare variables at the top of the scope to avoid problems associated with variable declaration and assignment.
// bad
function() {
test();
console.log('doing stuff.. ');
/ /.. other stuff..
var name = getName();
if (name === 'test') {
return false;
}
return name;
}
// good
function() {
var name = getName();
test();
console.log('doing stuff.. ');
/ /.. other stuff..
if (name === 'test') {
return false;
}
return name;
}
// bad
function() {
var name = getName();
if (!arguments.length) {
return false;
}
return true;
}
// good
function() {
if (!arguments.length) {
return false;
}
var name = getName();
return true;
}
Copy the code
- All of the
const
和let
grouping
// bad
let a
const b
let c
const d
let e
// good
const b
const d
let a
let c
let e
Copy the code
- Do not chain assignments to variables
Reason: Variable chain assignment creates hidden global variables
// bad
(function example() {
// JavaScript interprets this as
// let a = ( b = ( c = 1 ) );
// The let keyword only applies to variable a; variables b and c become
// global variables.
let a = b = c = 1} ())console.log(a) // throws ReferenceError
console.log(b) / / 1
console.log(c) / / 1
// good
(function example() {
let a = 1
let b = a
let c = a
}())
console.log(a) // throws ReferenceError
console.log(b) // throws ReferenceError
console.log(c) // throws ReferenceError
// the same applies for `const`
Copy the code
- Unused variables are not allowed
Reason: Variables declared but not used are usually errors of incomplete refactoring. Such variables waste space in the code and confuse the reader
// bad
var some_unused_var = 42
// Write-only variables are not considered as used.
var y = 10
y = 5
// A read for a modification of itself is not considered as used.
var z = 0
z = z + 1
// Unused function arguments.
function getX (x, y) {
return x
}
// good
function getXPlusY (x, y) {
return x + y
}
const x = 1
const y = a + 2
alert(getXPlusY(x, y))
// 'type' is ignored even if unused because it has a rest property sibling.
// This is a form of extracting an object that omits the specified keys.
const{ type, ... coords } = data// 'coords' is now the 'data' object without its 'type' property.
Copy the code
Hoisting
var
There is a case of variable promotion, i.evar
Declarations are promoted to the top of the scope, but their assignments are not. whileconst
和let
There is no such thing, they are givenTemporal Dead Zones, TDZTo understandTypeof is no longer secureIt is very important
function example () {
console.log(notDefined) // => throws a ReferenceError
}
function example () {
console.log(declareButNotAssigned) // => undefined
var declaredButNotAssigned = true
}
function example () {
let declaredButNotAssigned
console.log(declaredButNotAssigned) // => undefined
declaredButNotAssigned = true
}
function example () {
console.log(declaredButNotAssigned) // => throws a ReferenceError
console.log(typeof declaredButNotAssigned) // => throws a ReferenceError
const declaredButNotAssigned = true
}
Copy the code
- The variable names of anonymous functions are promoted, but the function content is not
function example () {
console.log(anonymous) // => undefined
anonymous()
var anonymous = function () {
console.log('test')}}Copy the code
- The variable name of a named function expression is promoted, but the function name and function content are not
function example() {
console.log(named) // => undefined
named() // => TypeError named is not a function
superPower() // => ReferenceError superPower is not defined
var named = function superPower () {
console.log('Flying')}}function example() {
console.log(named) // => undefined
named() // => TypeError named is not a function
var named = function named () {
console.log('named')}}Copy the code
The comparison operator & equality
- use
= = =
和! = =
Rather than= =
和! =
, eslint:eqeqeq - Condition declarations for example
if
Will useToBoolean
This abstract method converts expressions to Booleans and follows the following rulesObjects
Is equal to thetrue
Undefined
Is equal to thefalse
Null
Is equal to thefalse
Booleans
Is equal to theBoolean value
Numbers
在+ 0
.0
Or,NaN
Is equal tofalse
In other casestrue
Strings
为' '
When is equal to thefalse
, it istrue
if ([0] && []) {
// true
// Arrays (even empty arrays) are objects, and objects are true
}
Copy the code
- Use shortcuts.
// bad
if(name ! = =' ') {
/ /... stuff...
}
// good
if (name) {
/ /... stuff...
}
// bad
if (collection.length > 0) {
/ /... stuff...
}
// good
if (collection.length) {
/ /... stuff...
}
Copy the code
A semicolon
- A semicolon must precede a self-executing function
const test = 'Uncle Tooth Course'; (() = > {
const str = 'Easy to learn'}) ();Copy the code
block
- Use curly braces for all multi-line blocks
// bad
if (test)
return false;
// good
if (test) return false;
// good
if (test) {
return false;
}
// bad
function() { return false; }
// good
function() {
return false;
}
Copy the code
annotation
- use
/ * *... * /
Make multi-line comments, including descriptions, specifying types, and parameter and return values
// bad
// make() returns a new element
// based on the passed in tag name
//
// @param <String> tag
// @return <Element> element
function make(tag) {
/ /... stuff...
return element;
}
// good
/**
* make() returns a new element
* based on the passed in tag name
*
* @param <String> tag
* @return <Element> element
*/
function make(tag) {
/ /... stuff...
return element;
}
Copy the code
- use
//
Comment a single line above the comment object, preceded by a blank line.
// bad
var active = true; // is current tab
// good
// is current tab
var active = true;
// bad
function getType() {
console.log('fetching type... ');
// set the default type to 'no type'
var type = this._type || 'no type';
return type;
}
// good
function getType() {
console.log('fetching type... ');
// set the default type to 'no type'
var type = this._type || 'no type';
return type;
}
Copy the code
- If you have a problem that needs to be reviewed or if you suggest a solution that needs to be implemented, add it at the beginning of your comment
FIXME
或TODO
Help others understand quickly
function Calculator() {
// FIXME: shouldn't use a global here
total = 0;
return this;
}
Copy the code
function Calculator() {
// TODO: total should be configurable by an options param
this.total = 0;
return this;
}
Copy the code
accessor
- Accessor functions for the property are not required
- Use getVal() and setVal(‘hello’) if you do have accessor functions.
// bad
dragon.age();
// good
dragon.getAge();
// bad
dragon.age(25);
// good
dragon.setAge(25);
Copy the code
- If the attribute is Boolean, use isVal() or hasVal()
// bad
if(! dragon.age()) {return false;
}
// good
if(! dragon.hasAge()) {return false;
}
Copy the code
- You can create get() and set() functions, but keep them consistent
function Jedi(options) {
options || (options = {});
var lightsaber = options.lightsaber || 'blue';
this.set('lightsaber', lightsaber);
}
Jedi.prototype.set = function(key, val) {
this[key] = val;
};
Jedi.prototype.get = function(key) {
return this[key];
};
Copy the code
The constructor
- Assigning methods to an object stereotype, rather than overwriting the stereotype with a new object, causes inheritance problems.
function Jedi() {
console.log('new jedi');
}
// bad
Jedi.prototype = {
fight: function fight() {
console.log('fighting');
},
block: function block() {
console.log('blocking'); }};// good
Jedi.prototype.fight = function fight() {
console.log('fighting');
};
Jedi.prototype.block = function block() {
console.log('blocking');
};
Copy the code
- Method can return
this
Help methods can be linked.
// bad
Jedi.prototype.jump = function() {
this.jumping = true;
return true;
};
Jedi.prototype.setHeight = function(height) {
this.height = height;
};
var luke = new Jedi();
luke.jump(); // => true
luke.setHeight(20) // => undefined
// good
Jedi.prototype.jump = function() {
this.jumping = true;
return this;
};
Jedi.prototype.setHeight = function(height) {
this.height = height;
return this;
};
var luke = new Jedi();
luke.jump()
.setHeight(20);
Copy the code
- You can write a custom toString() method, but make sure it works and has no side effects.
function Jedi(options) {
options || (options = {});
this.name = options.name || 'no name';
}
Jedi.prototype.getName = function getName() {
return this.name;
};
Jedi.prototype.toString = function toString() {
return 'Jedi - ' + this.getName();
};
Copy the code
reference
Google JavaScript Style Guide
Aotu front-end code specification
javascriptCodeStyle
Quotes.
Thinking is the most important, other Baidu, Bing, StackOverflow, Android documents, autoJS documents, and finally in the group to ask — fang Shu tutorial
The statement
This tutorial is intended for learning purposes only and is not intended for any other use